GORM如何确保相关对象属性的唯一性 [英] GORM how to ensure uniqueness of related objects property
问题描述
我试图让我的头部围绕GORM和关系映射。关系工作正常,但有一个问题。我似乎无法确保每个 MailAddress
添加到 MailingList
都有一个唯一的地址。注意:在 MailAddress.address上没有唯一的约束
。
class MailAddress {
字符串名称
字符串电子邮件
static belongsTo = MailingList
静态约束= {
姓名空白:true
电子邮件电子邮件地址:true,blank:false
}
}
class MailingList {
字符串名称
static hasMany = [地址:MailAddress]
静态映射= {
地址cascade:'all-delete-orphan'
}
静态约束= {
空白名称:false
}
ibaralf的答案是一个自定义验证器。
MailingList
类用于验证所有地址( MailAddress
)是否具有唯一的电子邮件地址。 / p>
我将这个约束添加到 MailingList
类中并且它工作正常。
静态约束= {
空白名称:false
地址(验证者:{
if(!it ){
//如果集合为空,则验证为TRUE
//防止NULL异常
返回true
}
//获取集合列表中的所有电子邮件地址
def addressCollection = it * .email
//与仅具有唯一地址的集合比较
return addressCollection == addressCollection.unique()
} )
}
更多信息可以在这里找到 http://grails.org/doc/2.2.0/ref/Constraints/validato r.html
I'm trying to get my head around GORM and relational mapping. The relationships are working fine but there is one problem. I can't seem too ensure that every MailAddress
added to MailingList
has a unique address. What would be the must efficient way to do this?
Note: There is no unique constraint on MailAddress.address
. Identical addresses can exist in the same table.
class MailAddress {
String name
String email
static belongsTo = MailingList
static constraints = {
name blank:true
email email:true, blank:false
}
}
class MailingList {
String name
static hasMany = [addresses:MailAddress]
static mapping = {
addresses cascade: 'all-delete-orphan'
}
static constraints = {
name blank:false
}
}
As mentioned in the comments by @ibaralf the answer is a custom validator.
The MailingList
class needed to validate if all addresses (MailAddress
) have a unique e-mailaddress.
I added this constraint to the MailingList
class and it worked.
static constraints = {
name blank:false
addresses(validator: {
if (!it) {
// validates to TRUE if the collection is empty
// prevents NULL exception
return true
}
// Grab a collection with all e-mailaddresses in the list
def addressCollection = it*.email
// Compare to a collection with only unique addresses
return addressCollection == addressCollection.unique()
})
}
More info can be found here http://grails.org/doc/2.2.0/ref/Constraints/validator.html
这篇关于GORM如何确保相关对象属性的唯一性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!