2013-03-12 177 views
0

我試圖讓我的頭圍繞着GORM和關係映射。關係工作正常,但有一個問題。我似乎無法確保每MailAddress添加到MailingList有一個唯一的地址。要做到這一點必須有效的方法是什麼?GORM如何確保相關對象的唯一性屬性

注意:MailAddress.address沒有唯一的限制。相同的地址可以存在於同一個表中。

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

正如@ibaralf的評論所述,答案是一個自定義驗證器。 MailingList類需要驗證,如果所有地址(MailAddress)具有唯一的電子郵件地址。

我將這個約束添加到MailingList類,它的工作。

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

更多信息可以在這裏http://grails.org/doc/2.2.0/ref/Constraints/validator.html

0

有一個獨特的約束,你可以添加:

static constraints = { 
    name blank:true 
    email email:true, blank:false, unique: true 
} 

=>提上了電子郵件變量的唯一約束(獨特:真正)。這將阻止相同的電子郵件地址被保存在表格中。

+0

發現這就是問題所在。目前的表格允許我目前無法更改的重複項目。我只想在郵件列表中的地址之間實現唯一性 – Bart 2013-03-12 21:33:05

+1

如果我正確理解了您的意思,那麼您希望hasMany關聯具有唯一性。如果是這種情況,你可以看看這個答案http://stackoverflow.com/questions/4041939/how-to-set-uniqueness-at-db-level-for-a-one-to-many-association – ibaralf 2013-03-12 21:47:27

+0

謝謝提到那個帖子!我前幾天讀過它,但它讓我很頭疼,因爲提供的例子不起作用。所以我回到了文檔並找出了它。謝謝您的幫助。 – Bart 2013-03-13 06:26:07