Slinker009
Slinker009

Reputation: 105

How to get this data in relation models with Sails.js+Angular.js and RestAngular

How to get data of this models:

//User.js
module.exports={
name:{
type:'string'
},
pets:{
collection:'pet',
via:'owner'
},
cars:{
collection:'car',
via:'owner'
}
}

//Pet.js
module.exports={
name:{
type:'string'
},
owner:{
model:'user' 
}, 
doctors:{
collection:'doctor',
via:'pets'
}
};

//Car.js
module.exports={
color:{
type:'string'
},
owner:{
model:'user'
}
}
//doctor.js
module.exports={
name:{
type:'string'
},
pets:{
collection:'pet',
via:'doctors'
}
    };

Using RestApi routes to consume with Restangular, How to get all pets with the owner has car with blue color? how to work with multiple relation ( pets<-owner->cars)

Using RestApi routes to consume with Restangular, How to get all user with the pet has relation with a Mr XYZ doctor?how to work with multiple relation ( user -> pets <-> doctors)

thanks for your attention, if my question need improve, please comment and I will correct any issue.

Upvotes: 1

Views: 148

Answers (1)

Wulf Solter
Wulf Solter

Reputation: 714

Deep Queries are not supported yet, one day.

Why not something like:

/// Find all blue cars and get their owners
Cars.find({color:'blue'}).populate('owners').exec(function(err, bluecars) {

  // unique list of owners
  var owners = _.uniq(bluecars, function(el) {
    return el.owner.id;
  });

  // get all complete owners, with pets + cars
  async.map(
    owners,
    function(cb) {
      Owners.findOne({id: el.id})
        .populate('pets')
        .populate('cars')
        .exec(function(err, data) {
        cb(err, data);
      }
    },
    function(err, results) {
      // this is now a collection of all owners that have blue cars
      // from this you can see all their pets
      console.log(results);
    });
});

Yes you are making a lot of calls to the DB, but it's pretty straightforward and legible.

Once performance becomes an issue, and hopefully Owners,Cars&Pets are all on the same database you can write your own query using joins.

Upvotes: 2

Related Questions