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

219
Views
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
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!