Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

272
Views
How to join the same table 2 times with different aliases and conditions using Sequelize?

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:

  • have at least one project, which is connected to some topic on condition (where name='D');
  • include all 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?

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!