John
John

Reputation: 93

NodeJS Loopback - How do I filter models by its relations

I have an EUser model with a belongsTo relationship with userRole. I want to retrieve all the EUsers that have userRole.codeName == "Admin"

I can't find an example in the documentation for something like this...

What I've tried so far:

server.models.EUser.find({
    include: {
        relation: 'userRole',
        where: {
            codeName: 'Admin'
        }
    }
}, function(err, users){
    console.log(users);
});

However this doesn't seem to achieve the correct result.

I have verified that my relationship is defined properly as I can use the "include" filter properly in basic cases.

Upvotes: 2

Views: 1283

Answers (1)

IvanZh
IvanZh

Reputation: 2290

You couldn't get EUsers, filtered by property of related model, via EUser.find. Include filter just adds related models to returned instance.

Try to add userRole hasMany EUser relation as 'EUsers' and find 'Admin' userRole, including related EUser objects:

// assuming that userRole hasMany EUser as EUsers
userRole.find({ 
    where: { codeName: 'Admin' }, 
    include: 'EUsers' 
})

Upvotes: 1

Related Questions