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

后端 未结 2 437
广开言路
广开言路 2020-12-21 15:24

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

相关标签:
2条回答
  • 2020-12-21 15:38

    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.

    0 讨论(0)
  • 2020-12-21 15:54

    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});

    0 讨论(0)
提交回复
热议问题