sequelize.js - Sequelize include 包含来自连接表的记录

标签 sequelize.js

两个模型具有多对多关系,其中一个 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 记录的原因是什么,我该如何摆脱它?

最佳答案

你试试看,让我知道。我在这个 post 找到了解决方案

let products = await db.Product.findAll({ 
  include: [
    {
      model: db.Category, 
      attributes: ['id'], 
      required: true,
      through: {attributes: []}
    }]
});

关于sequelize.js - Sequelize include 包含来自连接表的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54878291/

相关文章:

javascript - 在没有模型 :generate? 的情况下在 Sequelize 中创建新模型

sql - 使用所需的 : true generates invalid join 对嵌套包含进行 Sequelize

node.js - Sequelize,原始查询按 daterange

mysql - 在 MySQL 中存储 Node.js 缓冲区的最佳实践

node.js - Sequelize : "Include unexpected" on associated table query

node.js - Nodejs Sequelize 有很多问题

node.js - "TypeError: Cannot read property ' 为多个请求推送 ' of null"

node.js - Nodejs - Sequelize hasMany 急切加载

node.js - 如何在 sequelize 中创建模型之间的关联

node.js - 如何在 node.js sequelize 库中测试所有复制服务器的连接