LoopbackJS: HasAndBelongsToMany, how to query/filter by property of relation?

情到浓时终转凉″ 提交于 2020-01-10 05:27:26

问题


I'm currently working on my first Loopbackjs project and am facing a seemingly simple issue: Let's say I have a model "Post" and a model "Tag". A Post has and belongs to many tags.

Now I need to list all posts with specific tags. I just can't figure out how to create a query with Loopback that achieves this. I thought it would work something like this, but it doesn't: Posts.find( {where: {tag.id: {inq: [1, 4]}}} ); 

I would greatly appreciate any help.


回答1:


It's not as easy as it should be to carry out a filter on some related properties. There is a pull request outstanding but it's been open for a long time now. As far as I can see, the only way of filtering is on the main model, so you could do:

Tags.find({"include":"posts","where":{"id":{"inq":[1, 4]}}})

Unfortunately you would need to do additional work to get a nice list of Posts from the results you get back.

EDIT You can alternatively get all Posts and only bring back the tags that match your query using scope, with the following:

Posts.find({
    "include": { "relation": "tags", 
                    "scope": { 
                        "where": {
                            "id": { "inq": [1, 4]}
                        }
                    }
                }
});

In the callback of the query, you can tidy up the result with the following code before returning it:

var finalresult = instance.filter(function(post) {
    return post.toJSON().tags.length > 0;
});

The benefit is that the results returned are formatted as you would expect. However, the performance of my second example may be extremely poor, as it will always return all of your Posts, unless you specify a filter or paging at the Post level. It's basically a Left Join, where as you want an Inner Join, which Loopback just can't do at the moment.




回答2:


I've come here with the same issue, but after some research I got to this solution.

I'm gonna use an example: model Provincias hasAndBelongsToMany Cantones.

In order to get: /api/Provincias/1/cantones

You can use in your Angular code:

Provincias.cantones({'id': 1});



来源:https://stackoverflow.com/questions/32903293/loopbackjs-hasandbelongstomany-how-to-query-filter-by-property-of-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!