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

时间:2013-12-06 12:04:44

标签: grails gorm

我在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属性定义约束......?     建议如何编写约束以避免类别

的重复值

1 个答案:

答案 0 :(得分:0)

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

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
       }
   }