sequelize.js - Sequelize include 包括连接表中的记录
问题描述
两个模型具有多对多关系,其中一个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
记录的原因是什么,我该如何摆脱它?
解决方案
你试试,让我知道。我在这篇文章中找到了解决方案
let products = await db.Product.findAll({
include: [
{
model: db.Category,
attributes: ['id'],
required: true,
through: {attributes: []}
}]
});
推荐阅读
- data-structures - 从自相交多边形中裁剪闭合多边形的算法
- java - Java eclipse PAHO 验证发布是否成功
- javascript - 在 cubejs 中构建正确的模式 sql
- python - 读取数据集的前几列和行而不是整个数据集
- typescript - 打字稿错误:“一个类只能实现一个对象类型或对象类型与静态已知成员的交集。” 实施部分时
- python - 关闭循环线程使脚本冻结
- c++ - 返回从函数内的新结构创建的结构
- python-3.x - 如何在 tkinter 中使用 4x4 薄膜键盘
- c# - 使用 SemaphoreSlim 限制并行任务的数量 - 为什么它会起作用?
- html - 显示间隙宽度较大:块