我想查询多对多模型。我的模型看起来像这样,
class Role {
String name
static hasMany = [users: User]
}
class User {
String name
String email
static hasMany = [roles : role]
static belongsTo = Role
}
以下是我在数据库中的表格,
role role_users user
--------------- ------------------------- ---------------------------------
|id |name | |role_id |user_id | |id |name |email |
--------------- ------------------------- ---------------------------------
|1 |Owner | |1 |1 | |1 |Harry |harry@mail.com |
|2 |Designer| |2 |2 | |2 |Hermione |hermione@mail.com|
|3 |Cleaner | |3 |3 | |3 |Ron |ron@mail.com |
--------------- ------------------------- ---------------------------------
这是我要查询的查询代码,
def myId = [1,2,3]
def users = User.executeQuery("select u from User as u join u.roles r where r.id = :id ", [id : myId])
如何查询数组中的条件?
答案 0 :(得分:1)
不是100%明确你的标准是什么,但如果我理解你的例子,那么我认为这样的事情会起作用:
def myIds = [2l, 3l]
def users = User.executeQuery("select u from User as u join u.roles as r where r.id in (:ids) ", [ids : myIds])
如果你真的不想使用HQL,你可以这样做:
def myIds = [2l, 3l]
def users = User.where {
roles {
id in myIds
}
}.list()
我希望有所帮助。
答案 1 :(得分:0)
使用in
代替=
来检查列表。请确保您要检查的列表包含项目(空列表会给您一个SQL错误):
def users = User.executeQuery("select u from User as u join u.roles r where r.id in :ids ", [ids: myIds])