Search code examples
angularjsloopbackjs

How to filter field in loopback from the include model?


I have this query:

UserModel.find({

    filter: {
        include: 
        [
            "communications",
             "roles"
        ],
        where : {
            "object_type" : 1
        }
    } 
}, function(data){
    $rootScope.users = data;
});

I want to get all the data from communications model filter by the field "object_type" but it doesn't work as I want.

My Communications model looks like this:

...
"properties": {
"object_type": {
  "type": "number"
},
"object_id": {
  "type": "number"
},
"communications_type_code": {
  "type": "number"
},
"address_type": {
  "type": "number"
},
"contact_value": {
  "type": "string"
},
"notes": {
  "type": "string"
},
....

Solution

  • To query related models you have to use relation scope. In your case that would be something like this:

    UserModel.find({
        filter: {
            include: 
            [
                {
                  "relation": "communications",
                  "scope": { 
                    "where": {"object_type": 1}
                  }
    
                },
                "roles"
            ]
        } 
    }, function(data){
        $rootScope.users = data;
    });
    

    Check the docs about "Querying related models"