我尝试从引用另一个表的表中进行选择.我在餐桌食品和餐桌配料之间存在多对多的关系.
I tried to select from a table with reference another table. I have a relationship many-to-many between table food and table Ingredients.
食物模型:
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模型:
Food_ingredients model:
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 }); };我的问题是,我不知道如何使用续集自然地联接此表.我尝试过这样的事情:
My problem is that I don't know how to make a natural join on this tables with sequelize. I tried something like this:
Food.findAll({include: [ { model: Food_Ingredients } ]}).then(responseWithResult(res)) .catch(handleError(res));但是我收到此错误:
food_incredients与食物无关!
food_incredients is not associated to food!
那么,我该如何用续集查询呢?
So, I how can I query that with sequelize?
谢谢.
推荐答案似乎您没有定义食品和配料之间的多对多关联.总之,您需要在模型中添加以下内容:
It doesn't seem like you defined the many-to-many association between food and ingredients. In summary, you need to add something like this to your models:
食物模型:
Food.belongsToMany(Ingredients, { through: Food_ingredients});成分模型:
Ingredients.belongsToMany(Food, { through: Food_ingredients});然后,当您要查询时,您不包括直通"模型,而是关系中的另一个模型.就您而言:
Then, when you want to query, you don't include the "through" model, but the other model in the relation. In your case:
Food.findAll({include: [ { model: Ingredients }]}).then(responseWithResult(res)).catch(handleError(res));Sequelize将为您做连接.请注意,如果给您的关系起别名,例如:
Sequelize will do the join for you. Note that if you give your relationship an alias, like:
Food.belongsToMany(Ingredients, {as 'someAlias', through: Food_ingredients});您需要在别名中添加该别名:
You need to add that alias in your include:
Food.findAll({include: [ { model: Ingredients, as 'someAlias' }]}).then(responseWithResult(res)).catch(handleError(res));更多推荐
从多对多关系中选择续集
发布评论