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

220
Vistas
Sequelize: Many to many relationship with two foreign keys

I have two tables related through a relationship table. On the relationship table there are two foreign keys for the same table.

  • Factors
  • Models
  • Models_has_Factors

Models_has_Factors contains foreign keys:

  • ref_models_mhf
  • ref_factors1_mhf
  • ref_factors2_mhf

I want to select models including the factors. I can't in any way have an implementation where sequelize returns the correct data without the configuration raw: true, but this returns multiple objects for the same model, which is not ideal. Is there a way to return only one object for each model, with an array of factors associated to them?

I'll leave my current implementation bellow but I already tried to change the relationship implementation to one using "belongsToMany()" instead but still no luck.

Factor association to models_has_factors

Factors.hasMany(models.models_has_factors, {
    foreignKey: { name: "ref_factors1_mhf" },
    as : "ref_factor1"
  })

  Factors.hasMany(models.models_has_factors, {
    foreignKey: { name: "ref_factors2_mhf" },
    as : "ref_factor2"
  })

Models_has_Factors associations

Models_has_Factors.belongsTo(models.models, {
    foreignKey: { name: "ref_models_mhf" }
  });

  Models_has_Factors.belongsTo(models.factors, {
    foreignKey: { name: "ref_factors1_mhf" },
    as: "factor1"
  });

  Models_has_Factors.belongsTo(models.factors, {
    foreignKey: { name: "ref_factors2_mhf" },
    as: "factor2"
  });

Models

 Models.hasMany(models.models_has_factors, {
    foreignKey: { name: "ref_models_mhf" }
  });

Getter

db.models.findAll({
  where: {
    id_models: id,
  },
  include: {
    model: models.models_has_factors,
    include: [{
      model: models.factors,
      as: 'factor1'
    }, {
      model: models.factors,
      as: 'factor2'
    }]
  }
})
about 4 years ago · Juan Pablo Isaza
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