【发布时间】:2020-09-01 04:46:36
【问题描述】:
我使用了一个使用两个外键引用同一模型的续集模型。我在创建父模型时没有问题。但是当我阅读它们时,它会给出错误提示 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
})
})
【问题讨论】:
标签: node.js sequelize.js