【问题标题】:How to fix Sequelize nested includes not working with limit/order/attributes?如何修复 Sequelize 嵌套包括不使用限制/订单/属性?
【发布时间】:2019-06-21 17:32:54
【问题描述】:

我有一些相互关联的模型,我需要在某个请求中全部获取它们。我需要在它的基本上所有部分上使用limitorderattributes,但这会导致嵌套包含吓坏了,我不完全确定它有什么问题。

它并没有真正打印任何错误或任何东西,模型要么没有被包含在响应中(即它们是空的),要么它们被包含但像 order/limit 这样的东西被忽略了。

我已经尝试过使用subQueryseparate 等...这些都不起作用。

有问题的查询;

const categories = await models.Category.findAll({
  attributes: ['id', 'title', 'description'],
  order: [['title', 'ASC']],
  include: [
    {
      model: models.Product,
      attributes: ['id', 'title'],
      through: { attributes: [] },
      include: [
        {
          model: models.Price,
          attributes: ['id', 'amount', 'createdAt'],
          order: [['createdAt', 'DESC']],
          limit: 1,
        },
      ],
    },
  ],
});

协会;

models.Category.belongsToMany(models.Product);
models.Product.belongsToMany(models.Category);

models.Product.hasMany(models.Price);
models.Price.belongsTo(models.Product);

我希望上面提供的查询返回;

  • Category 的升序基于title
  • ProductCategory 内部,具有 idtitle 属性。
  • PriceProduct 内,具有idamountcreatedAt 属性,降序顺序基于createdAt,限制为1。

【问题讨论】:

  • 您可以在问题中添加原始查询吗?
  • @NimishGupta 我想我可以吗?但在哪一部分?所有这些或只是我需要订购的那些?我使用 raw 的唯一问题是有时会搞砸 json 格式。
  • 您能解释一下为什么 through: { attributes: [] } 包含在 Product 中吗?至于belongsToMany 关联,根据文档,through 缺少“需要定义。Sequelize 以前会尝试自动生成名称,但这并不总是会导致最合乎逻辑的设置。” docs.sequelizejs.com/manual/tutorial/…
  • order,我猜limit 也是findAll 参数的属性,所以你需要将orderlimit 移到include 之外。在这里检查。 github.com/sequelize/sequelize/issues/4553
  • 正如@Emma 所说,您需要将orderlimit 移动到包含的同一级别。 Here 是实际的订购文档

标签: mysql node.js sequelize.js


【解决方案1】:

为了使查询按Product.Price.createdAt 排序,请将[models.Product, models.Price, 'createdAt', 'DESC'] 添加到order。至于限制:为了限制包含的模型,您需要将其作为单独的查询运行,因此将separate: true 添加到包含中。

代码:

const categories = await models.Category.findAll({
  attributes: ['id', 'title', 'description'],
  order: [['title', 'ASC'], [models.Product, models.Price, 'createdAt', 'DESC']],
  include: [
    {
      model: models.Product,
      attributes: ['id', 'title'],
      through: { attributes: [] },
      include: [
        {
          model: models.Price,
          attributes: ['id', 'amount', 'createdAt'],
          separate: true,
          limit: 1,
        },
      ],
    },
  ],
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    • 2017-08-03
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    相关资源
    最近更新 更多