【问题标题】:Query many to many with Sequelize in Nodejs/Express application在 Nodejs/Express 应用程序中使用 Sequelize 查询多对多
【发布时间】:2018-12-11 08:14:11
【问题描述】:

我正在使用 MySQL 和 Sequelize 构建 Nodejs/Express 后端,但我正在努力使用通过关系进行查询的语法。

我有一个类别表、一个媒体(图像)表和一个连接表 MediaCategory。我有一个包含类别 ID 的 REST 路由,我想获取该选定类别的所有媒体条目。

我定义了模型,并在 app.js 中定义了以下定义

Media.belongsToMany(Category, {
  through: {
    model: MediaCategory,
    unique: false
  },
  foreignKey: 'category_id',
  constraints: false
});

Category.belongsToMany(Media, {
  through: {
    model: MediaCategory,
    unique: false
  },
  foreignKey: 'media_id',
  constraints: false
});

而我的 getCategoryImages 控制器方法是这样的:

exports.getCategoryImages = (req, res, next) => {
  const categoryID = req.params.category;
  console.log("const categoryID: ", categoryID);

  Category.findAll({
    include: [{
      model: Media,
      where: {
        id: categoryID
      }
    }]
  })
    .then(categoryImages => {
      if (!categoryImages) {
        const error = new Error('Could not find categoryImages.');
        error.statusCode = 404;
        throw error;
      }
      res
        .status(200)
        .json({
          message: 'Fetched category images successfully.',
          items: categoryImages,
        });
    })
    .catch(err => {
      if (!err.statusCode) {
        err.statusCode = 500;
      }
      next(err);
    });

};

我在 Postman 中对 URL localhost:8080/categoryImages/16 的响应是这样的:

{
    "message": "Fetched category images successfully.",
    "items": []
}

items 数组中应该返回几十条图像记录。

恐怕我很难理解通过连接表获取数据的语法,我希望有人能指出我偏离轨道的地方。

【问题讨论】:

  • 应该where: { id: categoryID } 不在包含范围内吗? (媒体没有 categoryID?)
  • 这是解决方案的一部分 - 谢谢!我还在 belongsToMany 定义中颠倒了 foreignKeys。

标签: mysql node.js sequelize.js


【解决方案1】:

事实证明,问题在于我在 app.js 中的两个关联定义中颠倒了外键

Media.belongsToMany(Category, {
  through: {
    model: MediaCategory,
    unique: false
  },
  foreignKey: '*media_id* not *category_id*',
  constraints: false
});

Category.belongsToMany(Media, {
  through: {
    model: MediaCategory,
    unique: false
  },
  foreignKey: '*category_id* not *media_id*',
  constraints: false
});

Media 使用“media_id”作为外键,Category 使用“category_id”,而不是像我最初尝试的那样。

正如 Emma 在上面的评论中指出的那样,where: { id: categoryID } 块需要在包含之外。

 Category.findAll({
    include: [{
      model: Media
    }],
    where: {
      id: categoryID
    }
  })

【讨论】:

    猜你喜欢
    • 2019-01-26
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    • 1970-01-01
    • 2016-07-19
    • 2018-02-28
    相关资源
    最近更新 更多