续集加入和关系

时间:2016-10-01 21:47:59

标签: node.js database join foreign-keys sequelize.js

我正在运行数据库,但我无法在两个表之间执行连接。我已经在其他两个表之间进行了连接,但是这个表没有用。

在我的db.js文件中,我在表之间建立了以下关系:

db.diet.hasMany(db.meal, {as : 'Diet', foreignKey : 'dietId'});

在我的server.js文件中,我正在尝试构建此查询:

db.meal.findAll({
    include : [db.diet],
    where : {
        dietId : idDiet
    }
}).then(function (meals) {
    res.json(meals)
});

这给了我以下错误:

ReferenceError: idDiet is not defined

我也试过像这样查询饮食表:

db.diet.findAll({
    include :[db.meal],
    where : {
        idDiet : dietId
    }
}).then(function (meals) {
    res.json(meals);
});

但它也给了我一个错误:

ReferenceError: dietId is not defined

关于如何改善这一点的任何想法?

非常感谢,任何帮助表示赞赏。如果需要更多信息,请告诉我。

1 个答案:

答案 0 :(得分:1)

此:

db.diet.hasMany(db.meal, {as : 'Diet', foreignKey : 'dietId'});

应该是这样的:

db.diet.hasMany(db.meal, {as : 'Meals'});

您说diet有许多meal模型称为Meals,因此您可以将Mealsdiet包含在一起。

db.diet.findAll({
  include: [db.meal] // include the meal in the query ("join")
}).then((diet) => {
  // diet.Meals is a array of "meal" models that
  // belongs to the queried "diet"
});

我在这里回答了类似这样的类似问题:https://stackoverflow.com/a/39822966/3254198

相关问题