如何修复 Sequelize 嵌套包含不使用限制/顺序/属性?

5 mysql node.js sequelize.js

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

它并没有真正打印任何错误或任何内容,模型要么不包含在响应中(即它们是空的),要么包含它们但忽略诸如订单/限制之类的内容。

我已经尝试过使用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,
        },
      ],
    },
  ],
});
Run Code Online (Sandbox Code Playgroud)

协会;

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

models.Product.hasMany(models.Price);
models.Price.belongsTo(models.Product);
Run Code Online (Sandbox Code Playgroud)

理想情况下,我希望返回上面提供的查询;

  • Category升序排列基于title.
  • Product里面Category带有属性idtitle
  • PriceProduct在属性idamount、 和的内部createdAt,降序基于createdAt、 且限制为 1。

Avr*_*ham 6

为了让查询排序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,
        },
      ],
    },
  ],
});
Run Code Online (Sandbox Code Playgroud)