gpt4 book ai didi

grails - 如何在Grails中使用@Validateable确保非域Command类的唯一性

转载 作者:行者123 更新时间:2023-12-02 15:28:14 25 4
gpt4 key购买 nike

我有以下...

@Validateable
class Command1{
List<Command2> subCommands
}

@Validateable
class Command2{
String name
Long id
}

现在,我想创建一个约束以确保subCommands中的项目具有唯一的名称。我的约束应该是什么样的?应该在Command1还是Command2上?

最佳答案

由于Command2不了解Command1,因此必须对Command1设置约束。您可以使用自定义约束来完成此操作,因为 unique 约束在数据库级别进行检查,并且仅适用于域对象。

@Validateable
class Command1{
List<Command2> subCommands

static constraints = {
subCommands validator: { val ->
val.unique(false) { it.name } == val
}
}
}

在Groovy shell 中测试,但在Grails中未测试:
list = [[name: 'foo'], [name: 'bar'], [name: 'baz']]
assert list.unique(false) { it.name } == list
list = [[name: 'foo'], [name: 'bar'], [name: 'bar']]
assert list.unique(false) { it.name } != list

false传递给 unique() 告诉它不要就地改变列表。

关于grails - 如何在Grails中使用@Validateable确保非域Command类的唯一性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24390298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com