【发布时间】:2019-06-21 17:32:54
【问题描述】:
我有一些相互关联的模型,我需要在某个请求中全部获取它们。我需要在它的基本上所有部分上使用limit、order 和attributes,但这会导致嵌套包含吓坏了,我不完全确定它有什么问题。
它并没有真正打印任何错误或任何东西,模型要么没有被包含在响应中(即它们是空的),要么它们被包含但像 order/limit 这样的东西被忽略了。
我已经尝试过使用subQuery、separate 等...这些都不起作用。
有问题的查询;
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。 -
Product在Category内部,具有id和title属性。 -
Price在Product内,具有id、amount和createdAt属性,降序顺序基于createdAt,限制为1。
【问题讨论】:
-
您可以在问题中添加原始查询吗?
-
@NimishGupta 我想我可以吗?但在哪一部分?所有这些或只是我需要订购的那些?我使用 raw 的唯一问题是有时会搞砸 json 格式。
-
您能解释一下为什么
through: { attributes: [] }包含在Product中吗?至于belongsToMany关联,根据文档,through缺少“需要定义。Sequelize 以前会尝试自动生成名称,但这并不总是会导致最合乎逻辑的设置。” docs.sequelizejs.com/manual/tutorial/… -
order,我猜limit也是findAll参数的属性,所以你需要将order和limit移到include之外。在这里检查。 github.com/sequelize/sequelize/issues/4553 -
正如@Emma 所说,您需要将
order和limit移动到包含的同一级别。 Here 是实际的订购文档
标签: mysql node.js sequelize.js