2011-06-24 88 views
0

我正在嘗試創建一個模型以傳遞給gsp視圖。我想在兩個表中做一個子查詢。我有兩個域,alum_profile和alum_position。 alum_profile有許多alum_position。 alum_position屬於alum_profile。在SQL如果我想創建一個結果集,我想有這樣的事情:幫助創建視圖模型

Select count(id), 
(Select CONCAT(first_name, ' ', last_name) 
    From alum_profile 
    where 
    alum_profile_id =alum_profile.id) as Person   
FROM alum_position 
GROUP BY alum_profile_id 
ORDER BY count(id) DESC  

如何做到這一點與HQL,並創建一個可以傳遞到GSP視圖模型。

感謝您的幫助 傑森
我使用的泉源,與MySQL和Grails的

+1

你有這些表的任何域類嗎? –

回答

0

從常規寫我讀過你的問題,你要顯示的配置文件的名稱列表,以及每個配置文件有多少個職位,按職位數量,順序排序。

首先,你需要的型號:

class AlumProfile { 
    String first_name 
    String last_name 

    def hasMany = [positions: AlumPosition] 
}; 

class AlumPosition { 
    String name // I just added this, no idea what you need in here 

    def belongsTo=AlumProfile 
}; 

現在您要創建通過位置計數排序AlumProfiles的列表。在您的控制器,您需要:

def allByPositionCount = { 
    def profiles = AlumProfile.list().sort([compare: { a,b -> a.positions.size().compareTo(b.positions.size()) }] as Comparator); 
    [ profiles: profiles ] 
} 

,這會使得allByPositionCount.gsp與包含「輪廓」成員是在正確的順序配置文件的列表中選擇型號,所以像:

<g:each in="${profiles}" var="profile" > 
    ${profile.first_name} ${profile.last_name} has ${profiles.positions.size()} positions 
</g:each> 

應該渲染你想要的。

+0

請注意,這是全部來自內存,所以請允許錯字或替代方法更「Groovy」。 – billjamesdev