0

I have models in Sails as follows:
User Model

attributes: {
    firstName: {
        type: 'string',
        required: true
    },
    lastName: {
        type: 'string',
        required: true
    },
    company: {
        model: 'Company'
    }  
}  

Company

 name: {
        type: 'string',
        required: true,
        unique: true
    },
 description: {
        type: 'string',
        required: true
     }  

In HQL queries, for getting a user working in a specific company, we use something like this:

Select * from User where company.name=?  

How can I achieve same in Sails, Right now there are two queries which I am running, one to get User and then another to get company for that user. Is there any way both can be combined in one?

and one more thing, how does waterline deal with scenarios where in we need to get something out of a foreign key directly i.e. If I get user data, then can I get company details by just calling:

User.findOne({id:1}, function(err, res){
    //Res contains user data with just companyId now, 
    //how can i get whole company object here  
    var companyName = res.company.name; //This is not working currently
})
Abhishek
  • 1,999
  • 5
  • 26
  • 52

1 Answers1

0

Try something like this:

User.findOne({id: 1})
    .populate('company')
    .exec(function(err, user) {
        if(err){
            //handle errors      
        }else{
            //do stuff
        }
    });

This should get the values from the association (foreign key).

amarprabhu
  • 350
  • 3
  • 10