3

I am trying to build a simple application using loopback.io as process of my learning. I have set up the project, created models and apis are working fine.

Now I am trying to create a custom api which can get the data from two different models by making a join query. So i have a two models

stories : id, title, noteId

notes : id , desc

i have stories.js file as

module.exports = function(Stories) {

    Stories.list = function(cb) {
        // make a join query
    };
    
    Stories.remoteMethod(
        'list', {
            http: {
                path: '/list',
                verb: 'get'
            },
            returns: {
                arg: 'list',
                type: 'array'
            }
        }
    );
};

In general i will make a join in php api but here i am bit confused.Can i pass a raw query to database here or does loopback has some different way of achieving this. Any help would be appreciated.

Community
  • 1
  • 1
DomincJune
  • 931
  • 9
  • 15
  • Are you trying to join two models in Loopback or run raw SQL against it? – JSimonsen Aug 26 '15 at 20:09
  • I just want each record in the result containing all the columns from stories and all the columns from notes. Either join the models or running raw sql query which everywork.. – DomincJune Aug 27 '15 at 08:42

1 Answers1

4

You don't need to pass sql query. You can query data using PersistedModel find method by using include filter

In order to use include filter you have to create model relation.

For example:

Note relation:

"relations": {
  "stories": {
    "type": "hasMany",
    "model": "Story",
    "foreignKey": "noteId"
  }
},

Query:

Note.find({include: ['stories']}, function(err, data) { ... });
A.Z.
  • 1,638
  • 2
  • 18
  • 27
  • Hi A.Z i already did that. I have stories => "relations": { "notes": { "type": "hasMany", "model": "notes", "foreignKey": "id" } }, and in notes => "relations": { "stories": { "type": "belongsTo", "model": "Stories", "foreignKey": "noteId" } }, did no help – DomincJune Aug 27 '15 at 08:43
  • 1
    You did not setup your relation correctly. Put the same foreign key in hasMany and belongsTo relation. Story hasMany notes using storyId foreign key, and Note belongsTo Story using storyId. This will add storyId field to note table which will be used for "include" filter. – A.Z. Aug 28 '15 at 07:32