问题
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
}
}
回答1:
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
回答2:
There is a unique constraint you can add:
static constraints = {
name blank:true
email email:true, blank:false, unique: true
}
=> put the unique constraint on the email variable (unique: true). This would prevent identical email addresses to be saved in the table.
来源:https://stackoverflow.com/questions/15371949/gorm-how-to-ensure-uniqueness-of-related-objects-property