2011-06-24 89 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