gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:36:33 26 4
gpt4 key购买 nike

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

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

我已经尝试过使用 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 内的 Product,具有属性 idtitle
  • Product 内的 Price 具有属性 idamountcreatedAt,基于 createdAt 降序排列,限制为 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,
},
],
},
],
});

关于mysql - 如何修复 Sequelize 嵌套包含不使用限制/顺序/属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54406660/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com