如何在 Grails 中对域类中的关系施加约束?
我有一个像这样的域三域类:
Tasks.groovy
class Tasks {
static belongsTo = [ user : User ]
//other fields
Date startDate
Date endDate
}
User.groovy
class User {
//relationships. . . .
static belongsTo = [ company : Company, role : Role, resource : Resource]
static hasMany = [ holidays : Holiday, tasks : Tasks]
//other fields
}
Holiday.groovy
class Holiday {
static belongsTo = User
Date startDate
Date endDate
//other fields
}
现在,当我创建一个 Tasks< /code> 实例,我想设置一个约束,使
Tasks
startDate
和 endDate
不属于 User< /代码>的
假期
的startDate
和endDate
。如果有则抛出并出错。
我想要一种方法来将此约束施加在我的域类本身上(即在 Tasks
上)。
可以这样做吗?
提前致谢。
I have a domain three domain class like this :
Tasks.groovy
class Tasks {
static belongsTo = [ user : User ]
//other fields
Date startDate
Date endDate
}
User.groovy
class User {
//relationships. . . .
static belongsTo = [ company : Company, role : Role, resource : Resource]
static hasMany = [ holidays : Holiday, tasks : Tasks]
//other fields
}
Holiday.groovy
class Holiday {
static belongsTo = User
Date startDate
Date endDate
//other fields
}
Now when I create a Tasks
instance, I want to put a constraint such that the Tasks
startDate
and endDate
doesn't fall within the User
's Holiday
s startDate
and endDate
. And throw and error if it has.
I want a way to put this constraint on my domain class itself(i.e on Tasks
).
Is it possible to do so?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用自定义验证器来完成此操作。
您可以将自定义验证逻辑封装为闭包。您还必须为 endDate 添加类似的逻辑。
You can accomplish this using a custom validator.
You can encapsulate your custom validation logic as a closure. You will have to add similar logic for endDate as well.
我会在用户域中使用 createTask 函数,因为任务不应该摆弄迄今为止已删除的变量(self -> User -> Holiday -> startDate)。
很明显,用户知道假期何时开始和结束,因此可以轻松验证新任务的给定开始和结束日期。
I would go with having a
createTask
function in the User domain, since Task should not be fiddling with variables that are so far removed (self -> User -> Holiday -> startDate).It is quite clear that the User knows when its holiday starts and ends and thus would easily validate the given start and end dates for a new Task.