【发布时间】:2019-09-13 13:04:24
【问题描述】:
我有一个名为 Experience 的模型,它通过 ExperienceCategory 表与模型 Category 有一个 belongsToMany 关联。对于体验,我正在尝试使用它所属的类别获取体验详细信息。有些我正在使用include: [{model: model.Category}] 来实现这一点。现在,该关联正在工作并且它正在正确获取类别,但问题是它提供了体验模型的多个对象,每个类别一个。以下是我的代码的一些摘录:
model.Experience.findAll({
include: [
{
model: model.Category
}
]
}).then(experiences => {
res.json({experiences: experiences});
})
这就是我定义关联的方式:
经验.js:
Experience.belongsToMany(models.Category, {
through: 'ExperienceCategory',
foreignKey: 'experience_id',
});
category.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"
}
]
}
您可以看到,体验 ID 23 重复了两次,因为有两个不同的类别。我可以在数组中获取类别吗?
提前致谢。
【问题讨论】:
标签: node.js express sequelize.js