gpt4 book ai didi

node.js - Sequelize - 尝试使用 'include' 获取相关对象的belongsToMany 关系

转载 作者:行者123 更新时间:2023-12-03 22:26:33 26 4
gpt4 key购买 nike

我有一个名为 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',
});

类别.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});
})

关于node.js - Sequelize - 尝试使用 'include' 获取相关对象的belongsToMany 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57924195/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com