【问题标题】:How to retrieve list with max, offset and sort parameters with Grails ORM如何使用 Grails ORM 检索具有最大、偏移和排序参数的列表
【发布时间】:2015-08-31 11:32:00
【问题描述】:

我有一个带有UserGroup 域对象的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 对象,我可以检索带有maxoffsetsortBy 参数的成员吗?有点像...

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


【解决方案1】:

如果包含用户的所有组都保存在usergroups 字段中,您可以使用:

def query = User.where {
    usergroups { id == myGroup.id }
}

def users = query.list(max: 10, offset: 0, sort : "id")

【讨论】:

  • 谢谢,但这似乎只能检索到作为组创建者的User(即谁创建了myGroup.id)。我猜它会查询每个Userusergroups 并检查该用户组是否与myGroup 相同?
  • 为什么不在用户中添加另一个字段,称为joinedGroups,以便您可以使用此查询?我认为这个字段是映射这种情况的一种自然方式。在我的项目中,我使用这种结构来解决类似的问题。
  • 感谢您的建议,但添加joinedgroups 字段破坏了应用程序的另一部分。你能看看上面的编辑吗?可能是 User 现在定义的问题?
猜你喜欢
  • 2018-02-26
  • 2012-11-07
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2012-10-08
  • 2020-04-13
  • 1970-01-01
  • 2017-10-09
相关资源
最近更新 更多