【问题标题】:Sequelize include includes the record from the join tableSequelize include 包括连接表中的记录
【发布时间】: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


【解决方案1】:

你试试看并告诉我。我在post找到了解决方案

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

【讨论】:

    猜你喜欢
    • 2017-02-11
    • 2019-06-23
    • 2017-03-10
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 2018-08-29
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多