Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...