mysql - 从多对多关系中选择 Sequelize

标签 mysql database node.js many-to-many sequelize.js

我试图从引用另一个表的表中进行选择。我在餐 table 食品和餐 table 配料之间建立了多对多关系。

食物模型:

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
  });
};

食物成分模型:

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
  });
};

我的问题是我不知道如何使用 sequelize 在这个表上进行自然连接。我试过这样的事情:

Food.findAll({include: [
    {
      model: Food_Ingredients
    }
  ]}).then(responseWithResult(res))
     .catch(handleError(res));

但是我收到了这个错误:

food_incredients is not associated to food!

那么,我该如何使用 sequelize 查询它呢?

谢谢。

最佳答案

您似乎没有定义食物和配料之间的多对多关联。总之,您需要在模型中添加类似这样的内容:

食物模型:

Food.belongsToMany(Ingredients, { through: Food_ingredients});

成分模型:

Ingredients.belongsToMany(Food, { through: Food_ingredients});

然后,当你要查询时,你不包括“通过”模型,而是关系中的其他模型。在你的情况下:

Food.findAll({include: [
{
  model: Ingredients
}]}).then(responseWithResult(res)).catch(handleError(res));

Sequelize 将为您完成连接。请注意,如果您给关系起一个别名,例如:

Food.belongsToMany(Ingredients, {as 'someAlias', through: Food_ingredients});

您需要在您的包含中添加该别名:

Food.findAll({include: [
{
  model: Ingredients, as 'someAlias'
}]}).then(responseWithResult(res)).catch(handleError(res));

关于mysql - 从多对多关系中选择 Sequelize ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34463180/

相关文章:

Python-handler-socket (pyhs) 更新函数示例

javascript - $location.path 使用 Angularjs 单击按钮时未加载 html 文件

database - 图遍历 : How do I query for "friends and friends of friends" using Gremlin

r - R如何处理数据库连接的关闭

javascript - 类型 'array' 的属性在 Realm 对象服务器中具有未知的对象类型

node.js - MAC OS X "open APP.app"和 "APP.app/content/MacOs/APP"shell 脚本之间的差异

php - SQL 多查询特定

mysql - 使用 CURL 和 shell 脚本验证 mysql 数据库中 URL 的状态

php - mySQL 最后排序下划线

mysql - 关系数据库架构设计: Versioning properties on a large scale