Sails.js - One to Many mapping

Samuel Poirier picture Samuel Poirier · Aug 22, 2013 · Viewed 10.1k times · Source

Is there any way to do relation mapping between models in Sails.js?

Here is what I would like:

Video.js:

module.exports = {

  attributes: {

    filename: 'STRING',
    length: 'INTEGER',
    watchCount: 'INTEGER',
    extension: 'STRING'
    user: // I wan to reference to my User.js model
  }

};

And in my User.js:

module.exports = {

  attributes: {

    username: {
        type: 'email',
        required: true
    },
    password: 'STRING',
    videos: // I would like to have an array of videos after querying a user

  }

};

Answer

Luja Shrestha picture Luja Shrestha · Feb 20, 2014

You can use associations in sailsJs now by using the v0.10 branch https://stackoverflow.com/a/21822843/1585332
The mapping would be something like this..

Video.js

module.exports = {

  attributes: {

    filename: 'STRING',
    length: 'INTEGER',
    watchCount: 'INTEGER',
    extension: 'STRING'
    user:{
      model: "user"
    }
  }

};

User.js

module.exports = {

  attributes: {

    username: {
        type: 'email',
        required: true
    },
    password: 'STRING',
    videos:{
      collection: "video",
      via: "user"
    },

  }

};