1

I have documents of the form

challenge:

{
  "name": "challenge by abdul",
  "created_user_id": "1",
  "game_id": "123",
  "platform_id": "9857",
  "amount": 30

}

game: 
{
  "_id": "auto_generated",
  "name": "NFS",
  "version": "3",
}



platform:
{
  "_id": "auto_generated",
  "name": "ps2",
  "version": "sami"
}

I want to perform join query in sails and want result in below format

{
  "name": "challenge by abdul",
  "created_user_id": "1",
  "game_id": "123",
  "game_name":"NFS",
  "platform_name": "ps2",
  "platform_id": "9857",
  "amount": 30

}
Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
rash111
  • 1,307
  • 4
  • 19
  • 35
  • 1
    Have you read the Sails documentation on [models](http://sailsjs.org/documentation/concepts/models-and-orm), particularly the [associations](http://sailsjs.org/documentation/concepts/models-and-orm/associations) section? Using an ORM, you're not usually going to get an object like the one you're describing, but you'd get a `Challenge` model object with `game`, `platform` and possibly `user` properties which are themselves objects containing the info you want. Take a look at the docs and see if you still have questions about how to form your models and queries. – sgress454 Sep 15 '15 at 16:13

1 Answers1

3

There is no join in Sails but populate. So you need make associations between models and populate them. Example:

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

    version: {
      type: 'string'
    },

    game: {
      model: 'Game',
      via: 'platform'
    }
  }
};

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

    version: {
      type: 'string'
    },

    platform: {
      model: 'Platform',
      via: 'game'
    }
  }
};

You can write following code then:

// api/controllers/AnyController.js
module.exports = {
  index: function(req, res) {
    Game
      .findOne({name: 'MY_GAME'})
      .populate('platform')
      .then(function(game) {
        console.log(game); // Game model
        console.log(game.platform); // Platform model
        return game;
      })
      .then(res.ok)
      .catch(res.negotiate);
  }
};
Eugene Obrezkov
  • 2,910
  • 2
  • 17
  • 34