【问题标题】:How To Put A Constraint On Relationships In A Domain Class, In Grails?如何在 Grails 中对域类中的关系进行约束?
【发布时间】:2012-02-24 05:56:52
【问题描述】:

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

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 实例时,我想设置一个约束,使 Tasks startDateendDate 不属于 UserHolidays startDateendDate。如果有,则抛出错误。

我想要一种方法将这个约束放在我的域类本身上(即Tasks)。

可以吗?

提前致谢。

【问题讨论】:

    标签: grails groovy constraints grails-domain-class grails-validation


    【解决方案1】:

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

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

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

    【讨论】:

    • 不错!将一些逻辑封装到 User 类中可能会更好,这样代码会变得更加清晰并尊重得墨忒耳法则。类似startDate(validator: { startDate, self -&gt; self.user.canStartTaskAt(startDate) }) :)
    【解决方案2】:

    我会在 User 域中使用 createTask 函数,因为 Task 不应该摆弄到目前为止已删除的变量(self -> User -> Holiday -> startDate)。

    很明显,用户知道假期的开始和结束时间,因此很容易验证新任务的给定开始和结束日期。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-25
      • 2014-12-09
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 1970-01-01
      相关资源
      最近更新 更多