Sequelize include包含来自连接表的记录

时间:2019-02-26 04:05:26

标签: 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记录的原因是什么,我该如何摆脱它?

1 个答案:

答案 0 :(得分:0)

您尝试一下并让我知道。我在此post

找到了解决方案
let products = await db.Product.findAll({ 
  include: [
    {
      model: db.Category, 
      attributes: ['id'], 
      required: true,
      through: {attributes: []}
    }]
});