中为同一模型引用多外键属性时出错"/>
在Sequelize中为同一模型引用多外键属性时出错
我使用一个序列化模型,该模型使用两个外键引用同一模型。我在创建父模型时没有问题。但是,当我阅读它们时,出现错误,提示Cannot read property 'name' of undefined.
这里是我的模型定义以及如何选择它。
'use strict';
module.exports = (sequelize, DataTypes) => {
const Product = sequelize.define('Product', {
//common fields
}, {});
Product.associate = function(models) {
// associations can be defined here
Product.belongsTo(models.Unit, {
as: 'stockUnit',
foreignKey: 'stockUnitFk'
})
Product.belongsTo(models.Unit, {
as: 'retailUnit',
foreignKey: 'retailUnitFk'
})
};
return Product;
};
-
'use strict';
module.exports = (sequelize, DataTypes) => {
const Unit = sequelize.define('Unit', {
name: {type: DataTypes.STRING, unique: true},
}, {});
Unit.associate = function(models) {
// associations can be defined here
};
return Unit;
};
-
Product.findAll({inculde: [Unit]}).then(products => {
products.forEach(element => {
console.log(element.stockUnit.name) //this gives an error
})
})
回答如下:尝试一下
Product.findAll({ include: [{ model: Unit, as: 'stockUnit' }] }).then(products => {
})
如果关联是别名的(使用
as
选项),则必须指定包括模型时的别名。而不是通过模型直接使用include
选项,而应提供一个对象有两个选项:model
和as
请参见https://sequelize/master/manual/eager-loading.html#fetching-an-aliased-association
更多推荐
在Sequelize中为同一模型引用多外键属性时出错
发布评论