问题描述
旧数据库有两个表使用相同的列名作为主键。例如:
用户资料:
user_id int
visit_count int
我想创建双向的一对一关系。即
class User {
String name
UserProfile userProfile
static mapping = {
id column: 'user_id'
}
}
class UserProfile {
Integer visitCount
User user
static mapping = {
id column: 'user_id'
}
}
我希望能够引用“user.userProfile.visitCount”或“userProfile.user.name”。
我尝试了多种直接引用和关系描述符的组合,“hasOne”、“belongsTo”等。我认为这很简单,但找不到正确的语法。我遇到重复的列问题或缺少列名问题。任何帮助,将不胜感激。提前致谢。
解决方法
UserProfile 中的 User 将默认为 user_id,它与 UserProfile 的 id 列相同。因此,只需为用户引用添加一个列名,如下所示。
class UserProfile {
Integer visitCount
User user
static mapping = {
id column: 'user_id'
user column: 'useruser_id'
}
}
class User {
String name
static mapping = {
id column: 'user_id'
}
static hasOne = [ userProfile: UserProfile ]
}