【发布时间】:2019-02-26 16:33:27
【问题描述】:
两个模型具有多对多关系,其中Product 可以属于一个或多个Category,并由一个名为CategoryProduct 的表连接。
Category.associate = (models) => {
models.Category.belongsToMany(models.Product, { through: models.CategoryProduct } )
}
Product.associate = (models) => {
models.Product.belongsToMany(models.Category, { through: models.CategoryProduct } )
}
关联运行良好,但是当我使用include 时,结果集还包括连接表中的记录。
查询:
let products = await db.Product.findAll({
include: [
{
model: db.Category,
attributes: ['id'],
required: true
}]
});
我得到的回应:
{
"id": 237,
"otherProductColumns": "AndTheirValues",
"Categories": [
{
"id": 7,
"CategoryProduct": {
"id": 9,
"ProductId": 237,
"CategoryId": 7,
"createdAt": "2019-02-22T08:38:26.768Z",
"updatedAt": "2019-02-22T08:38:26.768Z"
}
}
]
}
我期望的回应:
{
"id": 237,
"otherProductColumns": "AndTheirValues",
"Categories": [
{
"id": 7
}
]
}
Sequelize 还返回整个 CategoryProduct 记录的原因是什么,我该如何摆脱它?
【问题讨论】:
-
你也可以添加`through:{attributes:['id']}'。我现在没有运行代码可以尝试。
-
如果您只需要一个类别 id,为什么不使用 group_concat 子查询在产品 findAll 中创建一个属性?
标签: sequelize.js