2012-09-18 20 views
0

我的下一個計劃:有秩序使用個createCriteria基於一個屬於關聯屬性

class UserProfile { 
    String title 
    String firstName 
    String lastName 
    static belongsTo = [user:User] 
    static constraints = { 
      user nullable:true , unique:true 
      title nullable:true, blank:true 
      firstName blank:false 
      lastName nullable:true, blank:true 
    } 
} 

class User { 
    String username 
    String password 
    boolean enabled 
    String email  
    static constraints = { 
     username size:6..40, blank:false, nullable: false, unique: true 
     email email:true, size:6..40, blank:false, nullable: false, unique: true 
     password size:5..64, password:true, blank:false, nullable: false 
    } 
    String toString(){username} 
} 

我需要有用戶的電子郵件下令UserProfile列表!

我嘗試:

UserProfile.createCriteria().listDistinct({ 
    if(params.orderBy){ 
     if(params.orderBy=="email"){ 
     //the exception says that the element has no such property to both cases  
      order("user.email", ascDesc) 
      //order("email", ascDesc)    
     }else{ 
      order("${params.orderBy}", ascDesc) 
     } 
    } 

}) 

所以當我想通過郵件訂購異常說​​,該元素有沒有這樣的屬性這兩種情況。注:ascDesc是一個變量String它可以ascdesc

回答

1

如果添加

createAlias('user', 'u') 

您的標準蓋頂部,那麼你應該能夠'u.email'訂購。

+0

出色答卷伊恩,只有它是隻需要添加此庫:'進口org.hibernate.criterion.CriteriaSpecification' –

+0

它不應該是必要添加任何進口。您的IDE可能會抱怨它不承認createAlias方法,但這是您爲動態DSL支付的代價 - grails會接受它。 –

1
if (params.orderBy == "email") { 
    user { 
     order ("email", ascDesc) 
    } 
} 

應該也可以工作,無需人工別名創建