我有一个User域类和一个List。
每个列表必须有一个作者(一个用户),每个用户都必须有一个“主要列表”。只有某些列表具有“primaryList”法规。
所以..像
用户:
列出primaryList
list :
用户作者
静态归属于=用户
当然,这不能按预期工作,因为这两种关系被错误地视为仅一种。我还应该在User上添加一个hasMany,并将其他属类添加到List ...,但是我不想使示例复杂化,因为我想从您那里得到正确的答案。
最佳答案
您可能需要使用mappedBy来说明用户和列表中的字段如何排列。这是我写的几个域,它们允许用户创作许多列表,但只将其中一个设置为“主要”。还有一些额外的可为空的约束,因此您可以使用支架式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
}
}
关于grails - Grails/GORM:映射这两个域的正确/最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5245545/