I am not able to query a many-to-many-association with Sequelize, and I speculate that it's related to a lower/uppercase-issue.
My alias and column name is camelCase ( extraId
), but the generated query seems to try TitleCased ( ExtraId
), but this is inferred from the error message below.
I want to query all Products
with their associated list of Extras
, and I try to do that as following:
const data = await models.Product.findAll(
{
include: [{
model: models.Extra,
as: 'extras'
}]
}
);
However, that gives the me the following error:
column extras->ProductExtras.ExtraId does not exist
I have three tables, Products
, Extras
, and their association table ProductExtras
defined as following:
const Product = sequelize.define('Product', {
name: {
allowNull: false,
type: DataTypes.STRING
}
}, {});
Product.associate = function(models) {
Product.belongsToMany(models.Extra, {
as: 'extras',
through: 'ProductExtras'
});
};
const Extra = sequelize.define('Extra', {
code: DataTypes.INTEGER,
desc: DataTypes.STRING
}, {});
Extra.associate = function(models) {
Extra.belongsToMany(models.Product, {
as: 'products',
through: 'ProductExtras'
})
};
const ProductExtras = sequelize.define('ProductExtras', {
productId: DataTypes.INTEGER,
extraId: DataTypes.INTEGER
}, {});
ProductExtras.associate = function(models) {
ProductExtras.belongsTo(models.Product, {foreignKey: 'productId'});
ProductExtras.belongsTo(models.Extra, {foreignKey: 'extraId'})
};
Any insights or solution to this issue would be greatly appreciated.
Have you tried adding a foreign key to the belongsToMany, as shown below? That's what I use to override the default column name for a join-table.
Product.associate = function(models) {
Product.belongsToMany(models.Extra,
{
as: 'extras',
through: 'ProductExtras',
foreignKey : 'extraId'
}
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.