2010-01-26 31 views
1

我是Grails,Groovy和GSP的新手。Grails - 檢查是否有父項

我有一個域類「ProductCategory」。

class ProductCategory { 

    static constraints = { 
    } 

    static mapping = { 
     table 'product_category'; 
     version false; 
     cache usage: 'read-only'; 
     columns { 
      parent column: 'parentid'; 
      procedure column: 'procid'; 
     } 

    } 

    static hasMany = [children:ProductCategory]; 

    ProductProcedure procedure; 
    Integer lineorder; 
    String name; 
    ProductCategory parent; 
    String templatelink; 
    char offline; 

    String toString() { 
     return id + " (" + name + ")"; 
    } 
} 

每個類別都可以有一個父類。我正在使用現有的數據庫,並且該表具有「parentid」列來執行此操作。當一個類別沒有父級(根級別)時,其對數爲0.

我有一個GSP嘗試顯示有關父級的數據(如果有的話)。

<g:if test="${category.parent}"> 
hello 
</g:if> 

我的印象是,這將測試存在。 它工作正常,如果類別有一個父,但只要parentid = 0,它爆炸。

No row with the given identifier exists: [ProductCategory#0] 

我試圖檢查== 0,但它沒有工作,我假設因爲'父'應該是一個對象。

那麼我怎樣才能讓它假設parentid = 0和parent = null一樣,還是沒有父親?

感謝

+0

你在哪裏設置的parentid = 0? – fabien7474 2010-01-27 01:08:24

+0

我不設置它。這是一個只讀應用程序,當類別沒有父項時,我現有的數據的parentid = 0。 – 2010-01-27 01:22:28

回答

1

我想我可能已經找到了答案:

parent column: 'parentid', ignoreNotFound: true; 

ignoreNotFound無處的文件,但它似乎工作!

0

parentid不應該等於0。它應該是null

我不明白你的問題,你怎麼能parentid == 0?

+1

因爲這是建立在現有的應用程序和數據庫模式之上的。就像我說的,在現有的模式中,parentid = 0意味着沒有父節點。 – 2010-01-27 01:13:27

-1

您不需要手動處理parentid。只要你定義這樣一個域類:

Class Foo { 
    Bar bar 
} 

Gorm/Grails會自動爲你創建一個外鍵列。如果你定義屬性爲空的:

Class Foo { 
    Bar bar 
    static constraints = { 
     bar(nullable:true) 
    } 
} 

...你可以將其設置爲null,測試空:

def f = new Foo(bar:null) 
if (f.bar == null) { ... } 
+0

此應用程序再一次建立在具有現有數據的現有數據庫之上。我不能讓Grails爲我創建/修改任何數據庫模式。 – 2010-01-27 18:07:38