Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a join query in loopback.io

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.

like image 267
DomincJune Avatar asked Mar 02 '26 23:03

DomincJune


1 Answers

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) { ... });
like image 63
A.Z. Avatar answered Mar 05 '26 12:03

A.Z.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!