gpt4 book ai didi

mysql - Grails 中属性的自引用关系?

转载 作者:行者123 更新时间:2023-11-30 01:19:34 27 4
gpt4 key购买 nike

我有以下自引用关系。一个用户可以有很多 friend 。

class User {

String name

hasMany = [friends: User]
}

Hibernate 在我的 MySql 数据库中所做的是创建一个表 user_user。

现在我想向 friend 关系添加一个属性,例如“Date lastUpdated”。我怎样才能做到这一点?

最佳答案

我在这里可能是不正确的,但看起来这是不可能的。原因是 user_user 表没有直接的域支持,因为它仅表示域之间的关系,而不表示域本身。

一种选择是管理映射器类中的关系,就像 Spring Security Core PersonAuthority class 的方式一样。

class Friendship implements Serializable {

User user //may need some mappedBy config in User class
User friend
Date lastUpdated

... //helper methods, see PersonAuthority class for example

static mapping = {
id composite: ['user', 'friend']
version false
}
}

由于它是一个实际的域类,因此您可以包含其他属性,例如 lastUpdated

更新评论:你真的应该看看PersonAuthority class举个例子 - 您不需要在 User 类中显式声明任何关系,因为它们现在由 Friendship 管理。您可以在 User 类中添加辅助方法来查询 Friendship 关系。

例如:

class User ...

...
Set<User> getFriends() {
Friendship.findAllByUser(this).collect { it.friend } as Set
}
}

关于mysql - Grails 中属性的自引用关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18698475/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com