Tuan
Tuan

Reputation: 81

how to use join to join two table in sails

I know that in sails i can use populate to join two models like describe in this link Sails model and orm for example i have 2 model:

// myApp/api/models/Pet.js
module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    color: {
      type: 'string'
    }
  }
}

and

// myApp/api/models/User.js
module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    age: {
      type: 'integer'
    },
    pony:{
      model: 'pet'
    }
  }
}

then

User.find({ name:'Mike' })
.populate('pony')
.exec(function(err, users) {}

will return something result like

 [{ 
  name: 'Mike',
  age: 21,
  pony: { 
    name: 'Pinkie Pie',
    color: 'pink',
    id: 5,
    createdAt: Tue Feb 11 2014 15:45:33 GMT-0600 (CST),
    updatedAt: Tue Feb 11 2014 15:45:33 GMT-0600 (CST) 
  },
  createdAt: Tue Feb 11 2014 15:48:53 GMT-0600 (CST),
  updatedAt: Tue Feb 11 2014 15:48:53 GMT-0600 (CST),
  id: 1 
 }]

in here pony is an object and i don't like that. I want return rerult something like this:

[{
    name: 'Mike',
    age: 21,
    name: 'Pinkie Pie',
    color: 'pink',
    id: 5,
    createdAt: Tue Feb 11 2014 15:45:33 GMT - 0600 (CST),
    updatedAt: Tue Feb 11 2014 15:45:33 GMT - 0600 (CST)
    createdAt: Tue Feb 11 2014 15:48:53 GMT - 0600 (CST),
    updatedAt: Tue Feb 11 2014 15:48:53 GMT - 0600 (CST),
    id: 1
}]

(all of them is property). So i think i would need join in this case. how can i do join ?

Upvotes: 1

Views: 3439

Answers (1)

Glen
Glen

Reputation: 1178

This question is already covered here. The answer demonstrates using .populate() in Sails for NoSQL DB's and .query() for SQL DB's.

An additional option, if you are using an SQL DB like MySQL, and this is a query that will be run frequently, is to create a view at DB level. You can find more on creating views in the MySql Documentation.

Upvotes: 3

Related Questions