如何在Grails中表示一对多,并对另一个域类进行约束?

如何在Grails中表示一对多,并对另一个域类进行约束?,grails,constraints,Grails,Constraints,我不确定这是否可行,但这里有一个例子 class Album { static hasMany = [ reviews: Review ] } class Author { static hasMany = [ reviews: Review ] } class Review { static belongsTo = [ album: Album, author: Author ] } 一个人可以为多张专辑写多篇评论,但我想限制他们只能为每张专辑写一篇评论。我一直在尝试用

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

class Album {
   static hasMany = [ reviews: Review ]
}

class Author {
   static hasMany = [ reviews: Review ]
}

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

一个人可以为多张专辑写多篇评论,但我想限制他们只能为每张专辑写一篇评论。我一直在尝试用constraints属性来实现这一点,但还没有找到任何方法。

我认为你不能用约束来实现它,除非你能在Review类上使用类似于多列唯一约束的东西。因此,唯一的约束将是在Review类上分组在一起的album和author属性


我没有试过,只是在这里的文档中看到了:

我假设
Author
类的一个实例是专辑评论的作者,换句话说就是“reviewer”。如果是这样,
Review
类中的以下验证器将确保作者尚未审阅相册。有关自定义验证器的更多信息,请参阅

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

只需添加一个唯一的约束

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

   static constraints = {
       album unique: 'author'
   }
}

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

Doh!让我的方式看起来很复杂:)投票给唐,他的方式更好!谢谢,我就知道是这样的。