【问题标题】:Sequelize include inside another includeSequelize include 在另一个 include 中
【发布时间】:2020-12-13 07:59:01
【问题描述】:

问题:

我无法使用 Sequelize@5.21.2 检索包含内的包含。 第一个包括它的确定。但是当我尝试获取其他包含时,我只收到 null。

代码:

let planCodes = ['monthly', 'annual'];

const plans = await Plan.findAll({
    where: {
        code: {
            [Op.or]: planCodes
        }
    },
    include: [{
        model: PlanItem,
        as: 'plan_items',
        include: [{
            model: Product,
            as: 'product',
        }]
    }]
});

模型关联:

计划

Plan.hasMany(PlanItem, { foreignKey: "plan_id" });

计划项目

PlanItem.hasOne(Product, { foreignKey: "plan_item_id" });

回应:

[
  {
    "id": 175231,
    "name": "mensal",
    "interval": "months",
    "interval_count": 1,
    "code": "monthly",
    "status": "active",
    "metadata": {},
    "created_at": "XXXX-XX-XX",
    "updated_at": "XXXX-XX-XX",
    "plan_items": [
      {
        "id": 190651,
        "plan_id": 175231,
        "product_id": 655939,
        "created_at": "XXXX-XX-XX",
        "updated_at": "XXXX-XX-XX",
        "product": null
      }
    ]
  }
]

我已经用数据库中的 ID 检查了所有详细信息,一切正常。

【问题讨论】:

  • 同时显示模型定义

标签: javascript node.js typescript sequelize.js


【解决方案1】:

我承认 Sequelize 喜欢消除关系中的所有自发性,但您应该在模型定义和查询中都使用别名。它们必须相同。我确定有一些余地,事实上,您正在返回plan_items 值。但无论是“最佳实践”还是“授权”,都试试吧:

Plan.hasMany(PlanItem, { as: "plan_items", foreignKey: "plan_id" });
PlanItem.hasOne(Product, { as: "product", foreignKey: "plan_item_id" });

// You may also try defining the Product/PlanItem relationship the other way
Product.belongsTo(PlanItem, { as: "plan_item", foreignKey: "plan_item_id" });

【讨论】:

  • 已经试过了,还是不行。解决方案是为每个产品创建另一个查询......不是我想要的方式,但现在解决了。无论如何感谢您的回答!
猜你喜欢
  • 1970-01-01
  • 2016-02-05
  • 1970-01-01
  • 2018-09-24
  • 2019-10-24
  • 1970-01-01
  • 2019-03-19
  • 2018-03-22
  • 2019-06-23
相关资源
最近更新 更多