2014-02-17 35 views
4

在閱讀grails官方指南時,我有關於belongsTo與多對一關係的問題。belongsTo可以爲空?

當我定義了兩個班,臉部和鼻子下面所列:

class Face { 

    String name 
    Nose nose 

    static constraints = { 
    } 
} 


class Nose { 

    String color 

    static belongsTo = [face: Face] 

    static constraints = { 
    } 
} 

我認爲我們可以讓臉部的實例有兩種方式:

  1. 同時使臉鼻子時間

    def rudolph = new Face(name: 'Rudolph', nose: new Nose('color': 'Red')).save(failOnError: true) 
    
  2. 使鼻子和麪部在序列

    def nose = new Nose(color: 'Red').save(failOnError: true) 
    def rudolph = new Face(name: 'Rudolph', nose: nose).save(failOnError: true) 
    

然而,無論是給我這樣的錯誤:

Fatal error running tests: Validation Error(s) occurred during save(): 
- Field error in object 'relationship.Nose' on field 'face': rejected value [null]; codes 

當然,如果我把鼻子上的限制,它的工作原理:

class Nose { 

    String color 

    static belongsTo = [face: Face] 

    static constraints = { 
     face nullable: true 
    } 
} 

我不是確定後退引用屬性是否必須始終爲空。

另一個問題是,下面的靜態屬性的作品,因爲它沒有「面子」屬性:

static belongsTo = Face 

如果沒有恢復參照屬性名,爲什麼我們定義屬於關聯的財產?

回答

0
  1. 在這種情況下,您定義一對一的關係,因此您不需要擁有「belongsTo」。你可以從「鼻子」類中刪除它,它會很好。更重要的是,您不必保存「鼻子」實例,只需創建它並將其添加到「臉部」並保存「臉部」實例即可。詳細信息:http://grails.org/doc/latest/ref/Domain%20Classes/hasOne.html

  2. 當您有一對多或多對多的關係時,需要定義「belongsTo」。它與保存和級聯刪除有關。鏈接爲「爲什麼」的問題:http://grails.org/doc/latest/ref/Domain%20Classes/belongsTo.html

+0

belongsTo從手冊中的描述描述了多對一的關係。我可以忽略這種關係嗎?我只需要考慮一對多。互聯網上的一些手冊/教程讓我感到困惑。謝謝。 – nasiajai

+0

在上面的問題中,您不需要belongsTo。至於其他情況下,你將不得不顯示代碼 – MeIr