symfony 2和doctrine,从另一个表中按joned记录的数量选择行表

时间:2014-12-10 09:33:58

标签: sql symfony orm doctrine-orm

基本上我有一个table1表和tabl2表。

一对多的关系

所以我想尝试选择

$em->createQueryBuilder()
            ->select('t1')
            ->from('AcmeAppBundle:Table1', 't1')
            ->orderBy('t1.id', 'DESC')
            ->getQuery()->getResult();

所以我需要相同的查询,但我需要订单来自table2的记录数 关系在实体中设置,如

* @ORM\OneToMany(targetEntity="Table2", mappedBy="something")

在原始查询中看起来像

SELECT table1.*  FROM table1 left join table2 on table1.id = table2.table1_id
                                group by (table2.table1_id)

3 个答案:

答案 0 :(得分:0)

$qb = $em->createQueryBuilder();

$qb
    ->select('t1')
    ->from('AcmeAppBundle:Table1', 't1')
    ->leftJoin('BLABLABundle:BlaEntity', 't2', 'WITH', 't1.id = t2.table1_id')
    ->orderBy('t1.id', 'DESC')
    ->groupBy('t2.table1_id');

$result = $qb->getQuery()->getResult();

答案 1 :(得分:0)

   $qb = $em->createQueryBuilder();

   $qb
    ->select('count(t2.id) count')
    ->from('AcmeAppBundle:Table1', 't1')
    ->join('AcmeAppBundle:Table1', 't2', 'WITH', 't1.id = t2.table1_id')
    ->orderBy('count', 'DESC')
    ->groupBy('t1.id');

像这样的东西。但没有经过测试。

答案 2 :(得分:0)

这会根据table2中的记录数来排序结果:

    $queryBuilder = $entityManager->createQueryBuilder()
            ->select('t1, COUNT(t2.id) AS myCount')
            ->from('AcmeAppBundle:Table1', 't1')
            ->leftJoin('t1.fields', 't2') //fields is the one to many field name for the target entity AcmeAppBundle:Table2
            ->groupBy('t1.id')
            ->orderBy('myCount', 'DESC');
    $result = $queryBuilder
                    ->getQuery()->getResult();