Grails / GORM:映射这两个域的正确/最佳方法是什么?

时间:2011-03-09 12:09:30

标签: grails gorm

我有一个用户域类和一个列表。

每个列表必须有一个作者(用户),每个用户必须有一个“主列表”。只有部分列表具有“primaryList”法规。

所以..像

这样的东西
 User:
    List primaryList

 List:
    User author

    static belongsTo = User

当然这不符合预期,因为这两种关系被误认为只是一种。我还应该在User上添加一个hasMany,在List上添加其他的belongsTo,但是我不想让这个例子复杂化,因为我想从你那里得到正确答案。

2 个答案:

答案 0 :(得分:3)

您可能需要使用mappedBy来解释用户和列表中的字段如何排列。以下是我编写的几个域,允许用户创作多个列表,但只设置一个为“主要”。有一些额外的可空约束,因此您可以使用scaffolded UI而无需进入鸡蛋和鸡蛋场景。

class User {
    String name
    FooList primaryList

    static hasMany = [authoredLists: FooList]

    static mappedBy = [primaryList: 'primaryOwner', authoredLists: 'author']

    static constraints = {
        primaryList nullable: true, unique: true
        authoredLists nullable: true
    }

    String toString() { name }
}

我将此类命名为“FooList”只是为了避免与标准List类混淆:

class FooList {
    static belongsTo = [author: User, primaryOwner: User]

    static constraints = {
        primaryOwner nullable: true, display: false
    }
}

答案 1 :(得分:2)

尝试使用地图belongsTo方法:

static belongsTo = [user:User]

Grails应该将2个属性视为单独的。

相关问题