从多对多关系中selectsequelize
我试图从表中select引用另一个表。 我在桌子食物和桌子成份之间有多对多的关系。
食物模型:
module.exports = function(sequelize, DataTypes) { return sequelize.define('food', { id: { type: DataTypes.INTEGER(10), allowNull: false, primaryKey: true, autoIncrement: true }, name_food: { type: DataTypes.STRING, allowNull: false } }, { tableName: 'food', freezeTableName: true }); };
Food_ingredients模型:
module.exports = function(sequelize, DataTypes) { return sequelize.define('food_ingredients', { id: { type: DataTypes.INTEGER(10), allowNull: false, primaryKey: true, autoIncrement: true }, food_id: { type: DataTypes.INTEGER(10), allowNull: false, references: { model: 'food', key: 'id' } }, ingredient_id: { type: DataTypes.INTEGER(10), allowNull: false, references: { model: 'ingredients', key: 'id' } } }, { tableName: 'food_ingredients', freezeTableName: true }); };
配料模型:
module.exports = function(sequelize, DataTypes) { return sequelize.define('ingredients', { id: { type: DataTypes.INTEGER(10), allowNull: false, primaryKey: true, autoIncrement: true }, name_ingredient: { type: DataTypes.STRING, allowNull: false } }, { tableName: 'ingredients', freezeTableName: true, timestamps: false }); };
我的问题是,我不知道如何在这个表上进行自然连接。 我尝试了这样的事情:
Food.findAll({include: [ { model: Food_Ingredients } ]}).then(responseWithResult(res)) .catch(handleError(res));
但是我收到了这个错误:
food_incredients是不相关的食物!
那么,我怎样才能查询与sequelize?
谢谢。
看起来你并没有定义食物和配料之间的多对多关系。 总之,你需要添加这样的东西到你的模型:
食物模型:
Food.belongsToMany(Ingredients, { through: Food_ingredients});
配料模型:
Ingredients.belongsToMany(Food, { through: Food_ingredients});
那么,当你想查询的时候,你不包括“through”模型,而是包含关系中的另一个模型。 在你的情况下:
Food.findAll({include: [ { model: Ingredients }]}).then(responseWithResult(res)).catch(handleError(res));
Sequelize会为你join。 请注意,如果你给你的关系一个别名,如:
Food.belongsToMany(Ingredients, {as 'someAlias', through: Food_ingredients});
你需要在你的include中添加这个别名:
Food.findAll({include: [ { model: Ingredients, as 'someAlias' }]}).then(responseWithResult(res)).catch(handleError(res));