node.js - Sequelize - 尝试使用“include”获取关联对象以获取 belongsToMany 关系
问题描述
我有一个名为 Experience 的模型,它通过 ExperienceCategory 表与模型 Category 有一个 belongsToMany 关联。对于体验,我正在尝试使用它所属的类别获取体验详细信息。我正在使用一些include: [{model: model.Category}]
来实现这一点。现在,该关联正在工作并且它正在正确获取类别,但问题是它提供了体验模型的多个对象,每个类别一个。以下是我的代码的一些摘录:
model.Experience.findAll({
include: [
{
model: model.Category
}
]
}).then(experiences => {
res.json({experiences: experiences});
})
这就是我定义我的关联的方式:
experience.js:
Experience.belongsToMany(models.Category, {
through: 'ExperienceCategory',
foreignKey: 'experience_id',
});
类别.js
Category.belongsToMany(models.Experience, {
through: 'ExperienceCategory',
foreignKey: 'category_id'
});
对上述查询的响应是:
{
"experiences": [
{
"id": 23,
"title": "Some title",
"notes": "These are notes",
"base_amount": 2000,
"is_disabled": false,
"is_deleted": false,
"createdAt": "2019-05-27T12:24:06.736Z",
"updatedAt": "2019-07-23T11:20:23.695Z",
"Categories.id": 4,
"Categories.name": "Trekking",
"Categories.is_disabled": false,
"Categories.is_deleted": false,
"Categories.createdAt": "2019-05-14T11:07:40.287Z",
"Categories.updatedAt": "2019-05-14T11:07:40.287Z",
"Categories.ExperienceCategory.experience_id": 23,
"Categories.ExperienceCategory.category_id": 4,
"Categories.ExperienceCategory.createdAt": "2019-05-27T12:24:06.806Z",
"Categories.ExperienceCategory.updatedAt": "2019-05-27T12:24:06.806Z"
},
{
"id": 23,
"title": "Some title",
"notes": "These are notes",
"base_amount": 2000,
"is_disabled": false,
"is_deleted": false,
"createdAt": "2019-05-27T12:24:06.736Z",
"updatedAt": "2019-07-23T11:20:23.695Z",
"Categories.id": 5,
"Categories.name": "Adventure",
"Categories.is_disabled": false,
"Categories.is_deleted": false,
"Categories.createdAt": "2019-05-14T11:07:40.287Z",
"Categories.updatedAt": "2019-05-14T11:07:40.287Z",
"Categories.ExperienceCategory.experience_id": 23,
"Categories.ExperienceCategory.category_id": 5,
"Categories.ExperienceCategory.createdAt": "2019-05-27T12:24:06.806Z",
"Categories.ExperienceCategory.updatedAt": "2019-05-27T12:24:06.806Z"
}
]
}
您可以看到 Experience ID 23 重复了两次,因为有两个不同的类别。我可以在数组中获取类别吗?
提前致谢。
解决方案
假设您在Experience
模型文件中有以下关联:
Experience.belongsToMany(models.Category, { through: 'ExperienceCategory', as: 'categories' });
然后,您需要执行以下操作才能在您的体验请求中列出类别:
models.Experience.findAll({
include: [
{ model: models.Category, as: 'categories' }
]
}).then(experiences => {
res.json({experiences: experiences});
})
推荐阅读
- php - 电子表格 xlsx 到 pdf 空白页
- nginx - 在 nginx 上强制请求超时?
- c# - 我可以在 ObjectCache 中存储 System.Timers.Timer 以供以后访问吗?
- pandas - Pandas:通过 groupby 对象迭代填充缺失值
- android - Android改变开关状态的颜色
- c# - 在鼠标悬停时更改按钮的背景
- java - JFileChooser 的限制
- java - Java:打印到屏幕被延迟
- conv-neural-network - 在 CNN 的情况下,向 Softmax 函数添加偏差有什么好处?
- razor - 如何在asp.net核心中定义返回html的函数