如何在Grails中表示一对多,并对另一个域类施加约束



我不确定这是否可能,但这里有一个例子。

class Album {
   static hasMany = [ reviews: Review ]
}
class Author {
   static hasMany = [ reviews: Review ]
}
class Review {
   static belongsTo = [ album: Album, author: Author ]
}

一个人可以为多个专辑写多个评论,但我想限制他们只能为每个专辑写一个评论。我一直在想一种方法来做到这一点与约束属性,但还没有能够拿出任何东西。

添加唯一约束

class Review {
   static belongsTo = [ album: Album, author: Author ]
   static constraints = {
       album unique: 'author'
   }
}

违反此约束时要解决的错误代码是review.album.unique

我假设Author类的一个实例是某张专辑评论的作者,换句话说就是"评论者"。如果是这样,Review类中的以下验证器将确保作者尚未评论过该专辑。有关自定义验证器的更多信息,请参阅http://grails.org/doc/1.3.x/ref/Constraints/validator.html。

class Album {
    static hasMany = [ reviews: Review ]
}
class Author {
    static hasMany = [ reviews: Review ]
}
class Review {
    static belongsTo = [ album: Album, author: Author ]
    static constraints = {
        author(validator: {
            val, obj ->
            for(review in obj.album.reviews){
                if(review.author == val){
                    return 'doubleEntry' //Corresponds to the "review.author.doubleEntry" error in your message.properties file which you will need to create by adding the line "review.author.doubleEntry=You cannot review this Album twice!" to your message.properties file.
                }
            }
            return true
        })
    } 
}

我不认为你可以强制它与约束,除非你可以得到的东西,如多列唯一的约束工作在复习类。因此,唯一的约束将是在Review类上组合在一起的专辑和作者属性。

我没有尝试过,只是在这里的文档中看到它:http://grails.org/doc/2.0.0.RC1/ref/Constraints/unique.html

最新更新