I have 3 tables:
User table:
---------------
userId | name
---------------
1 | Alice
2 | Bob
3 | Charly
---------------
Project table:
-------------------------------------
projectId | userId | state | color
-------------------------------------
4 | 1 | active | red
5 | 1 | closed | blue
6 | 2 | closed | green
7 | 3 | active | yellow
-------------------------------------
Topic table:
--------------------------------
topicId | projectId | topicName
--------------------------------
7 | 4 | D
8 | 4 | e
9 | 5 | D
10 | 6 | D
--------------------------------
Associations:
User.hasMany(model.Project)
Project.hasMany(model.Topics)
I'd like to find all Users who:
project, which is connected to some topic on condition (where name='D');projects that are in active state;So, as a result, I want to have
--------------------------------------
userId | userName | projectId | color
--------------------------------------
1 | Alice | 4 | red
2 | Bob | 6 | green
--------------------------------------
Something like this:
const users = await User.findAll({
include: [{
model: Project,
include: [{
model: Topics,
where: { name: 'D' },
attributes: [],
}],
attributes: [],
}, {
model: Project,
where: { status: 'active'},
required: false,
attributes: ['color'],
}]
})
I can solve this issue if I add one more association:
User.hasMany(models.Project, { as: 'ProjectTopics' });
and add to the query as: ProjectTopics on the 4th line.
But I don't want to have two associations to the same table with the same keys, just with different aliases.
There is a line in documentation:
options.include[].through.as
The alias for the join model, in case you want to give it a different name than the default one.
Could you help me to understand how it works and how I can use this for my issue?