[英]define one-to-many and many-to-many relationships in grails
i have two domain : User and Task such as : 我有两个域:用户和任务,如:
1) a user can be the author of many tasks 1)用户可以是许多任务的作者
2) a user can participate in many tasks,in the same time,a task can have many users which participate in 2)一个用户可以参加很多任务,一个任务可以同时有很多用户参与
so,i want to define a one-to-many for 1) and a many-to-many for 2) 因此,我想为1)定义一对多,为2)定义多对多
User{
static hasMany = [createdTasks : Task, //for one-to-many
assignedTasks : Task //for many-to-many
]
static mappedBy = [createdTasks : author]
}
Task{
User author
static hasMany = [assignedUsers : User]// for many-to-many
}
i think i have to define the owner side of my many-to-many relationship(assignedTasks-assgnedUsers) ? 我想我必须定义我的多对多关系(assignedTasks-assgnedUsers)的所有者端? anyone have a idea for defining the correct relationship satisfying my specification 1) and 2)?
有人有想法定义满足我的规格1)和2)的正确关系吗?
thanks :) 谢谢 :)
I think you could accomplish this an easier way: 我认为您可以通过一种更简单的方式完成此操作:
Really the relationships can just be on the task. 真正的关系可以只是在任务上。 The only reason to do what you are trying to do is to create a bi-directional relationship.
做您想做的事情的唯一原因是创建双向关系。 This can be achieved simpler with declaring methods on the user to get the objects you want.
通过在用户上声明方法以获取所需的对象,可以更轻松地实现此目的。
User{
Set<Task> getCreatedTasks() {
Task.findAllByAuthor(this)
}
Set<Task> getAssignedTasks() {
Task.executeQuery("""
Select t
from Task t join t.assignedUsers as tu
where tu = :user
""", [user: this])
}
}
Task{
User author
static hasMany = [assignedUsers : User]
}
Try this. 尝试这个。 Note the quotation in mappedBy.
注意在quotedBy中的引号。
User {
static hasMany = [
createdTasks: Task, // for one-to-many
assignedTasks: Task // for many-to-many
]
static mappedBy = [
createdTasks: 'author'
]
}
Task {
User author
static hasMany = [
assignedUsers: User // for many-to-many
]
static belongsTo = [
User
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.