LoopbackJS:HasAndBelongsToMany,如何通过关系属性查询/过滤器? [英] LoopbackJS: HasAndBelongsToMany, how to query/filter by property of relation?

查看:486
本文介绍了LoopbackJS:HasAndBelongsToMany,如何通过关系属性查询/过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在对我的第一个项目Loopbackjs和现在面临一个看似简单的问题:
比方说,我有一个模型邮报的典范变量。一个帖子已经和属于多个标签。

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.

现在我需要列出所有文章与特定的标记。我只是无法弄清楚如何创建一个环回查询实现这一目的。
我认为这会工作这样的事情,但事实并非如此:
Posts.find({其中:{tag.id:{INQ:[1,4]}}});

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

我将不胜AP preciate任何帮助。

I would greatly appreciate any help.

推荐答案

这并不容易,因为它应该是进行过滤的一些相关的属性。 有一个上拉未完成的请求,但它是开放的,现在很长一段时间。至于我所看到的,唯一的办法过滤在主模式,所以你可以这样做:

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

在查询的回调,你可以用下面的code收拾结果返回之前:

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.

这篇关于LoopbackJS:HasAndBelongsToMany,如何通过关系属性查询/过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆