我仍然试图将 menu_title 从关联的Menu模型转换为json。如果我使用下面描述的代码控制台显示错误
如果我已定义ER_BAD_FIELD_ERROR: Unknown column 'Products.MenuId' in 'field list'
,也{foreignKey: 'menu_id'}
。我做错了什么?
菜单型号:
module.exports = function(sequelize, Sequelize) {
var Menu = sequelize.define("Menu", {
owner_id: Sequelize.INTEGER,
menu_title: Sequelize.STRING,
}, {
classMethods: {
associate: function(models) {
Menu.hasMany(models.Product)
}
}
});
return Menu;
};
产品型号:
module.exports = function(sequelize, Sequelize) {
var Product = sequelize.define("Product", {
owner_id: Sequelize.INTEGER,
menu_id: Sequelize.INTEGER,
product_title: Sequelize.STRING,
}, {
classMethods: {
associate: function(models) {
Product.belongsTo(models.Menu, { foreignKey: 'menu_id'})
}
}
});
return Product;
};
然后在控制器内:
Menu.find({
where: { owner_id: req.user.id },
include: [
{ model: Product }
]
}).success(function(match) {
res.json(match.home);
});
感谢您的帮助!
答案 0 :(得分:4)
您需要在关系的两边包含外键
Menu.hasMany(models.Product, { foreignKey: 'menu_id'})
否则,sequelize假定从关系的菜单端查询时,外键被称为menuId