How do I search for elements whose collection contains another element in Grails?

时光怂恿深爱的人放手 提交于 2019-12-03 16:38:55

问题


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]

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

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.


回答1:


You can use this HQL query:

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



回答2:


In my opinion, this syntax is much cleaner:

User.withCriteria { followedUsers{ eq('id', userInstance.id) } }


来源:https://stackoverflow.com/questions/8946232/how-do-i-search-for-elements-whose-collection-contains-another-element-in-grails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!