从多对多关系中选择续集

时间:2015-12-25 13:14:51

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

我尝试从引用另一个表的表中进行选择。我在餐桌和餐桌配料之间有多对多的关系。

食物模型:

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

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

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

但我收到了这个错误:

  food_incredients与食物无关!

那么,我怎么能用sequelize查询呢?

感谢。

1 个答案:

答案 0 :(得分:2)

似乎你没有定义食物和成分之间的多对多关联。总之,您需要在模型中添加以下内容:

食物模型:

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

您需要在include中添加该别名:

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