'Sequilize query is returning only one row while using include in belongsToMany association
Context : I have this problem when I try to fetch a model with the through attribute, in my case the association table can have the composition (foreign key 1, foreign key 2) repeated several times with a different value for a custom association field
Note: I'm using SQlite as an SGBD
Here is the definition of the models / Association
export const Cap = sequelize.define('Cap', {
// Model attributes are defined here
ID: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: {
type: DataTypes.STRING(100),
unique: true,
allowNull: false
}
}
}, {
tableName: 'cap'
});
export const Assessment = sequelize.define('Assessment ', {
// Model attributes are defined here
ID: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
label: {
type: DataTypes.STRING(50),
unique: true,
allowNull: false
},
}, {
tableName: 'assessment '
});
export const CapAssessments = sequelize.define('CapAssessments ', {
// Model attributes are defined here
ID: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
cap: {
type: DataTypes.INTEGER
},
assessment: {
type: DataTypes.INTEGER
},
score: {
type: DataTypes.INTEGER
}
}, {
tableName: 'capAssessments '
});
Cap.belongsToMany(Assessment, { through: 'capAssessments ', as: 'hasKCMapping', foreignKey: 'cap'});
KeepCalmsAssessment.belongsToMany(Capability, { through: 'capAssessments ', as: 'belongsToCap', foreignKey: 'assessment'});
And here is the query that I used for retrieval:
let kcMapping = await Capability.findAll({
attributes: {
exclude: ['ID']
},
include: [
{
model: KeepCalmsAssessment,
as: 'hasKCMapping',
through: {
attributes: ['score']
},
}
]
});
The problem is that the query only display one result for the through table, when it should instead print two, here is the result obtained:
{
"name": "make-flow",
"hasKCMapping": [
{
"ID": 1,
"label": "culture",
"capAssessments ": {
"cap": 9,
"assessment": 1
}
}
]
},
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
