Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize :: Limit and Order INSIDE an Include[] construct

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:

  1. Load all Children for the User, sorted by name.
  2. For each Child, load the first three Profiles reverse sorted by id.

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?

like image 388
AweSIM Avatar asked Jul 09 '15 06:07

AweSIM


1 Answers

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?

like image 140
whitfin Avatar answered Nov 16 '22 01:11

whitfin