grails - 如何使用Grails ORM检索具有max,offset和sort参数的列表

标签 grails gorm

我有一个带有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

此查询之前有效,因此在mappedby中添加额外的User条目可能导致了此问题。 mappedby中的新User字段不正确吗?

最佳答案

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

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

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

关于grails - 如何使用Grails ORM检索具有max,offset和sort参数的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32310236/

相关文章:

hibernate - Grails在同一事务上分页数据库结果?

grails - 在Where查询中可以引用多少个关联级别是否有限制?

grails - Grails 3域类名为 “Application”的问题

java - Grails使用OutOfMemory删除级联树

eclipse - 在grails中使用graphql插件最终会导致:java.lang.ClassNotFoundException:org.grails.compiler.web.converters.RenderConverterTrait

apache - 带有 Tomcat/Apache ProxyPass 的 Grails URL

mongodb - GORM-获取域类属性的原始DB值

grails - 验证是否在服务测试中调用了保存

grails - 在Grails条件中的列组之间使用OR运算符

hibernate - 使用 “in”查询进行GORM的where闭包将在生成的SQL中删除where子句