问题
I have the following model hierarchy:
User.hasMany(Child);
Child.hasMany(Profile);
Once I have a User object loaded, I need to load its Children and their associated Profiles according to the following logic:
- Load all
Childrenfor theUser, sorted byname. - For each
Child, load the first threeProfilesreverse sorted byid.
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']]
});
});
});
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.
Is there a way to specify limit and order options right inside the include[] construct?
回答1:
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?
来源:https://stackoverflow.com/questions/31309369/sequelize-limit-and-order-inside-an-include-construct