如何使用Grails ORM

时间:2015-08-31 11:32:01

标签: 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字段是否不正确?

1 个答案:

答案 0 :(得分:1)

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

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

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