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

可紊 提交于 2019-12-06 22:55:54

问题


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?


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!