Doctrine为每位Master提供最新的一行详细信息

时间:2017-02-16 03:45:35

标签: symfony doctrine-orm greatest-n-per-group query-builder

我有像这样的QueryBuilder

$query = $this->getEntityManager()
  ->createQueryBuilder()
  ->select('partial master.{id,name}, partial detail.{id,name}')
  ->from('AppBundle:Master', 'master')
  ->leftJoin('master.detail', 'detail')
  ->orderBy('detail.id','DESC')
  ->getQuery();
return $query->getArrayResult();

主关系是OneToMany,详细关系是ManyToOne。 我试图得到一行细节,细节ID更高或更低。什么Querybuilder使这成为可能? 例如,我有这样的数据:

1.A, 1.B, 1.C, 2.A, 3.A, 3.C

我想要下面的结果

1.A, 2.A, 3.A

2 个答案:

答案 0 :(得分:1)

$query = $this->getEntityManager()
    ->createQueryBuilder()
    ->select('master.id, master.name, detail.id, detail.name')
    ->from('AppBundle:Master', 'master')
    ->leftJoin('master.detail', 'detail')
    ->groupBy('master.id')
    ->orderBy('detail.id','DESC')
    ->getQuery()
;

return $query->getArrayResult();

答案 1 :(得分:0)

获取您在DQL后使用的每个主行的最新详细信息

SELECT m,a 
FROM AppBundle\Entity\Master m
    LEFT JOIN m.detail a
    LEFT JOIN AppBundle\Entity\Detail b 
    WITH a.master = b.master 
    AND a.id < b.id
WHERE b.id IS NULL