Sails JS Waterline join of multiple models Sails JS Waterline join of multiple models express express

Sails JS Waterline join of multiple models


In SailsJS 0.10+ you can use model associations to do database joins. You can read more about them here: http://sailsjs.com/documentation/concepts/models-and-orm/associations

Basically you first define an association in your model;

var someModel = {  attributes: {    name: {      type: 'text'    }  }};var someOtherModel = {  attributes: {    name: {      type: 'text'    },    associationProp: {      model: 'someModel'    }  }};

In the code above someOtherModel contains association (relation) to someModel. To do a join query you can use .populate() method. For example retrieve all someOtherModel entities and populate associative properties;

someOtherModel.find().populate('associationProp').exec(...);

For MySQL and PSQL adapters there's also .query() method available where you can write some hand written SQL queries to be executed (this also works in sails <0.10);

Model.query(<sql query>, <optional data>, callback);