2015-02-24 107 views
0

我有很多一对多的关系:的Grails查询:获取关联对象的名单

class Project { 
    Set<PrincipalInvestigator> pis 
    : 

    static hasMany = [ pis:PrincipalInvestigator ] 
} 

class PrincipalInvestigator { 
    String name 
    : 
} 

我想返回属于一个预先定义的列表督察的独特和排序列表查询的项目。

一个天真的方法是迭代通过项目,并迭代通过他们的PI列表,同时删除欺骗。这样做的代码很简单,但速度很慢。

到目前为止,最好的有效的解决方案我能想出是:

def pi_ids = Project.createCriteria().list{ // find unique list of PI IDs 
    // project filters here, not relevant to the question 
    createAlias('pis', 'aka_pis', JoinType.LEFT_OUTER_JOIN) 
    isNotNull('aka_pis.id') 
    projections { 
     distinct('aka_pis.id') 
    } 
} 
def pi_list = PrincipalInvestigator.createCriteria().list{ // get PIs from list of IDs 
    inList('id', pi_ids) 
    order('name', 'asc') 
} 

我的解决办法是幅度快一个数量级,但它仍然是2个不同的查询。有没有办法在单个查询中获得相同的结果?

回答

0

解决我的问题是这样的HQL:

PrincipalInvestigator.executeQuery(
    "select distinct pi from Project p inner join p.pis as pi where p.id in :projectIds order by pi.name", 
    [projectIds:[1,2,3]]) 

该解决方案允许对不同的结果进行排序和内加入微调的所有空实例。感谢cfrick让我走上正轨。

0

使用executeQuery使查询变得更容易。沿着下面的东西应该工作:

PrincipalInvestigator.executeQuery("select distinct p.pis from Project p where p.id in :projectIds", 
    [projectIds: [1,2,3]]) 
+0

谢谢。你如何使PI列表唯一(编辑“选择不同”)并妥善排序? – sebnukem 2015-02-24 18:21:58

+0

@sebnukem编辑,只需添加'distinct' – cfrick 2015-02-24 18:29:30