Sahan
Sahan

Reputation: 1467

SailsJS manually populate records using Model.query

lets say i have this example as my app http://sailsjs.org/#!/documentation/concepts/ORM/Associations/OnetoMany.html

For some big reasons(complicated) I cannot use Model.populate() and I'm stuck in using Model.query()

Does anyone know how to get the result as User.find().populate('pets') Using Model.query() Please

Thank you

Upvotes: 4

Views: 596

Answers (1)

khalil
khalil

Reputation: 741

You can do it like waterline adapters do to populate OneToMany:

  1. Retrieve parents :
    select * from user ...
  2. Retrieve children for each parent in only one query to not overload DBMS:
    select * from pet where user = user1.id union select * from pet where user = user2.id union ... union select * from pet where user = userN.id.
  3. Regroup children by parentPk(you can use lodash or underscore.js functions to do it) Ex:

    users.forEach(function(user){ user.pets = _.filter(pets,function(pet){ return pet.user === user.id; }); });

Upvotes: 1

Related Questions