Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

278
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda