如何在 Grails 中对域类中的关系施加约束?

发布于 2025-01-08 06:57:54 字数 954 浏览 4 评论 0原文

我有一个像这样的域三域类:

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 startDateendDate 不属于 User< /代码>的假期startDateendDate。如果有则抛出并出错。

我想要一种方法来将此约束施加在我的域类本身上(即在 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 Holidays 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

十二 2025-01-15 06:57:54

您可以使用自定义验证器来完成此操作。

startDate(validator: {val, obj->
    obj.user.holidays.every{holiday-> val <= holiday.startDate || val >= holiday.endDate }
})

您可以将自定义验证逻辑封装为闭包。您还必须为 endDate 添加类似的逻辑。

You can accomplish this using a custom validator.

startDate(validator: {val, obj->
    obj.user.holidays.every{holiday-> val <= holiday.startDate || val >= holiday.endDate }
})

You can encapsulate your custom validation logic as a closure. You will have to add similar logic for endDate as well.

娜些时光,永不杰束 2025-01-15 06:57:54

我会在用户域中使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文