Sequelize :: Limit 和 Order INSIDE an Include[] 构造 [英] Sequelize :: Limit and Order INSIDE an Include[] construct
问题描述
我有以下模型层次结构:
I have the following model hierarchy:
User.hasMany(Child);
Child.hasMany(Profile);
一旦我加载了一个 User
对象,我需要根据以下逻辑加载它的 Children
及其关联的 Profiles
:p>
Once I have a User
object loaded, I need to load its Children
and their associated Profiles
according to the following logic:
- 为
User
加载所有Children
,按name
排序. - 对于每个
Child
,加载按id
反向排序的前三个Profiles
.
- Load all
Children
for theUser
, sorted byname
. - For each
Child
, load the first threeProfiles
reverse sorted byid
.
有没有办法限制和排序急切加载的Profiles
?我可以限制和排序 Children
但不能限制 Profiles
.
Is there a way to limit and sort the eager-loaded Profiles
? I can limit and sort the Children
but not the Profiles
.
user.getChildren({
limit: 10,
order: [['name', 'ASC']],
include: [{
model: Profile,
limit: 3, <-- HAS NO EFFECT!!!
order: [['id', 'DESC']] <-- HAS NO EFFECT!!!
}]
});
我可以使它工作的唯一方法是执行以下操作:
The only way I can make it work is by doing the following:
user.getChildren({
limit: 10,
order: [['name', 'ASC']]
}).then(function(children) {
user.children = children;
_.each(children, function(child) {
child.getProfiles({
limit: 3,
order: [['id', 'DESC']]
});
});
});
在我看来这很糟糕,并且需要额外的代码来确保在所有 Children
加载之前我不会访问 Children
.
This is both bad in my opinion and requires extra code to ensure I don't access the Children
before all Children
have been loaded.
有没有办法在 include[]
构造中指定 limit
和 order
选项?
Is there a way to specify limit
and order
options right inside the include[]
construct?
推荐答案
不确定 limit
,但我尝试了一个简单的 order
并且效果很好:
Not sure about limit
, but I tried with a simple order
and it worked fine:
user.getPets({
order: 'type ASC'
})
通过扩展,我会假设 limit 也有效?
By extension, I would assume limit works too?
这篇关于Sequelize :: Limit 和 Order INSIDE an Include[] 构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!