开发者

Help with Creating Models for Views

I am trying to create a Model to pass to a gsp view. I would like to do a sub query across two tables. I have two domains, alum_profile and alum_position. alum_profile has many alum_position's. alum_position belongs to alum_profile. In SQL if I wanted to create a result set, I would have something like this:

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      

How do I do this with HQL and create a model that can be passed to a gsp View.

Thanks for your help jason

I am using Spring Source, with MySQL and writing in groovy on grails


From what I've read of your question, you want to display a list of the Profile's names, along with how many Positions each Profile has, sorted by the number of positions, desc.

First, you need Models:

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
};

Now you want to create a list of the AlumProfiles sorted by position count. In your controller, you need:

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

This will render the allByPositionCount.gsp with the model containing the "profiles" member that is the list of profiles in the correct order, so something like:

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

should render what you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜