gpt4 book ai didi

grails - 如何在 grails 中编写 hasMany 属性的约束

转载 作者:行者123 更新时间:2023-12-03 03:46:17 24 4
gpt4 key购买 nike

我在 grails 应用程序中有三个类

class Category {
String name
}

class Application {
String name
static hasMany =[specialCategoryies:SpecialCategory]
}

class SpecialCategory {
Category category
Integer points
static belongsTo =[application:Application]
}

在这里,当我保存 applicationInstance 时,我不想保存重复项像 ..specialCategories 这样的specialCategories 值不具有相同的值再次类别值..

application.addToSpecialCategoryies(newSpecialCategory(category:Category.get(1),points:2))
application.addToSpecialCategoryies(newSpecialCategory(category:Category.get(1),points:3))

这里我的应用程序实例应该会出现类别值重复的错误。 那么如何定义域类中 hasMany 属性的约束......? 建议如何编写约束以避免类别的重复值

最佳答案

您可以尝试在“应用程序约束”部分中使用自定义验证器。例如,检查重复属性值的一种方法是将这些值收集到一个数组中,并将它们与相应的唯一数组进行比较(删除了重复元素):

class Application {

String name
static hasMany =[specialCategoryies:SpecialCategory]

static constraints = {
specialCategoryies validator: { specialCategories, obj ->

def specialCategoriesIdArray = specialCategories.collect {it?.category?.getId()}
return (specialCategoriesIdArray.size() == specialCategoriesIdArray.unique().size())?true:'application.validator.specialcategoryduplicate.error'

}
}
}

当尝试将特殊类别与现有类别一起保存时,保存时会抛出验证错误。您可以使用以下内容进行测试:

    def cat1 = new Category(name:"Cat 1").save(flush:true)
def cat2 = new Category(name:"Cat 2").save(flush:true)

def app = new Application()
app.name = "Test"

app.addToSpecialCategoryies(new SpecialCategory(category: Category.get(1), points:2))
app.addToSpecialCategoryies(new SpecialCategory(category: Category.get(2), points:2))
app.addToSpecialCategoryies(new SpecialCategory(category: Category.get(1), points:3))

if ( app.save(flush:true) ){
log.info "Saved!"
} else {
log.error "NOT Saved. Error:"
app.errors.each {
log.error it
}
}

关于grails - 如何在 grails 中编写 hasMany 属性的约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20423458/

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