2013-10-08 87 views
0

如果我有四個領域類是這樣的:Grails的查詢與父母

class Branch { 
    String name 
    static hasMany = [users:Users] 
    static mappedBy = [users:'branch'] 
    static mapping = {     
     id   column: 'f_branch_id' 
     name  column: 'f_name' 
    } 
} 
class Users { 
    String name 
    static hasMany = [account:Account] 
    static mappedBy = [account:'user'] 
    static belongsTo= [branch:Branch, title:Title] 
    static mapping = { 
     id   column: 'f_user_id', 
     name  column: 'f_name', 
     branch  column: 'k_branch_id' 
    } 
} 
class Account { 
    String username 
    static belongsTo = [user:Users] 
    static mapping = { 
     id    column: 'f_account_id' 
     user   column: 'f_user_id' 
     username  column: 'f_username' 
    } 
} 
class JoinTable implements Serializable { 
    Account account 
    Role role  
    static mapping = { 
     id    composite : ['role', 'account'] 
     role   column  :'k_role_id' 
     account   column  :'k_account_id' 
     version false 
    }  
} 

如何使用條件查詢 我嘗試這個過程,但失敗的別名問題

def criteria = JoinTable.createCriteria() 
    def list = criteria.list {    
     account { 
       user{ 
        branch{ 
         eq("id", "2") 
        } 
       } 
     } 
    } 
+0

類帳戶{ 字符串username 靜態屬於關聯= [用戶:帳戶] ?????也許[用戶:用戶] –

+0

謝謝@Andrii Olenchenko,但它不能解決我的問題 –

回答

0

我得到分支從JoinTable

class Branch { 
    String name 
    static hasMany = [users:Users] 
    static mapping = { 
     id   column: 'f_branch_id' 
     name  column: 'f_name' 
    } 
} 
class Title { 
    ... 
} 
class Users { 
    String name 
    static hasMany = [account:Account] 
    static belongsTo= [branch:Branch, title:Title] 
    static mapping = {...} 
} 
class Account { 
    String username 
    static belongsTo = [user:Users] 
    static mapping = {...} 
} 
class Role { 
    ... 
} 
class JoinTable implements Serializable { 
    Account account 
    Role role 
    static mapping = { 
     id    composite : ['role', 'account'] 
     role   column  :'k_role_id' 
     account   column  :'k_account_id' 
     version false 
    } 
} 

測試

@TestMixin(GrailsUnitTestMixin) 
@Mock([Act, Branch, Title, Users, Account, Role, JoinTable]) 
class EaseTests { 
void testCriteria(){ 
     10.times{ 
      def b = new Branch().save(validate:false, flush:true) 
      10.times{ 
       def u = new Users(branch:b).save(validate:false, flush:true) 
       10.times{ 
        def a = new Account(user:u).save(validate:false, flush:true) 
        def joinTableRow = new JoinTable(account: a).save(validate:false, flush:true) 
       } 
      }   
     }  

     def c = JoinTable.createCriteria() 
     def results = c{ 
      account{ 
        user { 
         branch{ 
          idEq(2l) 
         } 
        } 
      } 
     } 
     assert results 
    } 
} 
+0

謝謝@Andrii Olenchenko,但它不能解決我的問題,因爲我看到別名問題 –

+0

感謝@Andrii Olenchenko爲您的迴應,我嘗試您的程序 我在我的應用程序控制臺模式下看到類似這樣的內容 錯誤:'where子句'中的未知列'branch_ali3_.f_branch_id' 此處alies「branch_ali3_」在查詢中不存在 –