2016-02-17 28 views
4

我有Grails的2.0.3下面的語句的作品,我想通過標準的Grails如何讓正確加入withCriteria

def result = db.rows('SELECT a.description FROM public."Description" as a ' + 
         'INNER JOIN public."product" as b ' + 
         'ON a.product_code = b.product_code ' + 
         'WHERE a.product_code = ?',[productInstance.product_code]) 

Cuase,而不是返回描述來改變精
查詢: [說明],它返回說明:[description_fielddb:描述]

enter image description here

現在,在控制器我嘗試用以下標準

 List result = Description.withCriteria{ 
     product{ 
      eq('product_code', productInstance.product_code) 
     } 
     projections{ 
      property('description') 
     } 
     } 

更換,但產品似乎並不能夠訪問: enter image description here

Description.groovy

class Description { 

String product_code; 
String description; 

static belongsTo = [product : Product] 
    static constraints = { 
    product_code blank:false, size: 1..15 
    description blank:false, size: 1..16 

} 
} 

Product.grovy

class Product { 

String store 
String product_code 
int price 
String notes 


static hasOne = [description: Description] 

    static constraints = { 
    product_code blank:false, size: 1..15 
    price blank:false, scale: 2 
    store blank:false, size: 1..40 
    notes blank:true , size: 1..150 

} 



product_code blank:false, size: 1..15 
price blank:false, scale: 2 
store blank:false, size: 1..40 
notes blank:true , size: 1..150 

} 

}

我試圖grails clean

grails compile --refresh-dependencies 

我試圖從浴室,並重新導入刪除項目太

+0

您能否顯示域類的代碼描述和產品?你使用的是哪個版本的grails? –

+0

你能提供一個你正在做什麼的更大的圖片嗎?我覺得你使用Grails還是有點奇怪,但你卻繞過了其最好的特性之一:GORM/Hibernate。而你是領域模型沒有意義。我懷疑你正在使用現有的(aka。legacy)數據庫,這很好,但是需要仔細的域類映射才能使它工作。例如,如果'product_code'是產品表的主鍵,那麼GORM需要知道;默認情況下主鍵是'id'。 –

+0

在grails中我很新,你能告訴我爲什麼沒有意義嗎? –

回答

3

你正在創建一個非Grails的方式域和查詢。

的域必須正確

相關產品的映射是沒有必要的原因您的域名被稱爲產品爲好,Grails將生成表的「產品」。另一方面,你必須把它的描述聯繫起來。如果存在雙向關係。您必須使用「hasOne」

class Product { 

    String store 
    String product_code 
    int price 
    String notes 

    static hasOne = [description: Description] 

    //or directly as a property. Don't do this if you use belongsTo in the other domain. 
    //Description description 

} 

的描述屬於一種產品,因而它必須與爲「屬於關聯」

class Description { 

    String product_code 
    String description 

    static belongsTo = [product: Product] 

} 

如果你想獲得由產品代碼的所有描述中,您可以通過產品屬性在描述域中創建條件,並獲取描述域的描述屬性。只需執行以下操作:

List descriptions = Description.withCriteria{ 
    product{ 
    eq('product_code', productInstance.product_code) 
    } 
    projections{ 
    property('description') 
    } 
} 

您不需要在grails中爲該簡單查詢創建Sql查詢。

+0

正如你建議我只添加在類說明...靜態belongsTo = [產品:產品] ...但我得到> Groovy:明顯變量'產品'被發現在一個靜態範圍內,但沒有引用一個局部變量,靜態字段或類。可能的原因: –

+0

我更新我的問題也許可以更有用 –

+0

我現在很忙,但我可以嘗試以後重現錯誤。我能問你爲什麼從2.x版本開始使用Grails?我們正在使用3.x版本 – quindimildev