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'
}]
}
})