首页 > 解决方案 > 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记录的原因是什么,我该如何摆脱它?

标签: sequelize.js

解决方案


你试试,让我知道。我在这篇文章中找到了解决方案

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

推荐阅读