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

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

问题描述

我目前正在处理我的第一个 Loopbackjs 项目,但面临一个看似简单的问题:假设我有一个模型Post"和一个模型Tag".一个帖子拥有并属于多个标签.

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.

现在我需要列出所有带有特定标签的帖子.我只是不知道如何使用 Loopback 创建一个查询来实现这一点.我认为它会像这样工作,但事实并非如此:Posts.find( {where: {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]}}} ); 

我将不胜感激任何帮助.

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 您也可以获取所有帖子,并仅使用 scope 取回与您的查询匹配的标签,使用以下内容:

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.

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

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