如何在Grails中搜索集合中包含另一个元素的元素? [英] How do I search for elements whose collection contains another element in Grails?

查看:176
本文介绍了如何在Grails中搜索集合中包含另一个元素的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为User的域类,可以跟随其他User对象。它有这样的字段指定为:

Let's say I have a domain class called "User" which can follow other "User" objects. It does so having a field specified as:

def hasMany=[followedUsers:User]

我需要做相反的操作(找到跟随特定User对象的所有User对象),而不设置反向关系,因为它不是用例经常执行。我试图这样做,使用闭包:

I need to do the reverse (find all User objects that follow a specific User object) without setting up the reverse relationship, since it is not a use case performed often. I tried to do something like this, using closures:

User.findAll { it.followedUsers.contains(userInstance) }

,但这始终会返回数据库中的所有用户,我尝试使用HQL,但也失败了。

but this always returns all users in the database, regardless of their follow status. I tried doing with HQL but failed miserably as well.

任何人都可以给我一个简单的方法来实现这一点的一个快速指针?谢谢。

Could anyone give me a quick pointer on the simplest way to accomplish this? Thank you.

推荐答案

您可以使用此HQL查询:

You can use this HQL query:

User.executeQuery(
   'select u from User u where :follower in elements(u.followedUsers)',
   [follower: userInstance])

这篇关于如何在Grails中搜索集合中包含另一个元素的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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