【发布时间】:2015-08-31 11:32:00
【问题描述】:
我有一个带有User 和Group 域对象的grails 应用程序。 User 有许多 Group 对象,Group 对象包含许多 User 对象:
class User implements Serializable {
static constraints = {
usergroups nullable: true
}
static mapping = {
usergroups cascade: 'all-delete-orphan'
}
static hasMany = [
usergroups: Group
]
static mappedBy = [
usergroups : "creator"
]
}
class Group {
static belongsTo = [
creator : User
]
static hasMany = [
members : User
]
static constraints = {
creator nullable: false
members nullable: true, maxSize: 100
}
}
给定一个Group 对象,我可以检索带有max、offset 和sortBy 参数的成员吗?有点像...
def members = User.where {
/* how to specify only the users in 'group.members'? */
}.list(
max: max,
offset: offset,
sortBy : sortBy
);
编辑
为了尝试解决问题,我已将 User 类更改为包含 joinedgroups 字段...
class User implements Serializable {
static constraints = {
usergroups nullable: true
joinedgroups nullable: true
}
static mapping = {
usergroups cascade: 'all-delete-orphan'
}
static hasMany = [
usergroups: Group
joinedgroups: Group
]
static mappedBy = [
usergroups : "creator",
joinedgroups : "creator" // if I don't add this Grails complains there is no owner defined between domain classes User and Group.
]
}
但是现在当我尝试在我的应用程序的另一部分检索所有用户的 usergroup 对象时,只返回一个用户组...
def groups = Group.where {
creator.id == user.id
}.list(max: max, offset: offset, sort: sortBy); // should return 3 groups but now only returns 1
此查询以前有效,因此在 User 中添加额外的 mappedby 条目可能会导致问题。 User 中的新 mappedby 字段是否不正确?
【问题讨论】:
-
你试过
static mappedBy = [usergroups : "creator", joinedgroups : "members"]吗? -
确实有,谢谢。我收到一条错误消息,提示“在域类用户和组之间没有定义所有者”。如果我做
static mappedby = [usergroups : "creator", joinedgroups : "none"],我可以让它工作。老实说,我不知道为什么这样做会奏效(或者以后是否会导致另一个问题)。 -
如果您最初的问题的答案是正确的,请接受。
标签: grails grails-orm