【发布时间】: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