Sequelize :: 在 Include[] 结构中限制和订购 [英] Sequelize :: Limit and Order INSIDE an Include[] construct
问题描述
我有以下模型层次结构:
I have the following model hierarchy:
User.hasMany(Child);
Child.hasMany(Profile);
一旦我加载了 User
对象,我需要根据以下逻辑加载其 Children
及其关联的 Profiles
:>
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'
})
通过扩展,我会假设限制也有效?
By extension, I would assume limit works too?
这篇关于Sequelize :: 在 Include[] 结构中限制和订购的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!