为什么getResult()只返回一个只包含最后一条记录的数组?

时间:2016-09-23 08:46:00

标签: doctrine-orm symfony

我正在Symfony 3中编写一个控制台应用程序,但由于某种原因,我的查询结果只返回了数组中的1个结果,我确认在MySQL中运行它并得到几个结果。以下是相关代码:

$arr_id = array();
$em = $this->getContainer()->get('doctrine')->getManager();
$dql2 = 'SELECT r.productId as pid, COUNT(r.id) as cnt 
          FROM AppBundle:ReferralTrack r 
          WHERE r.productId in (:in) 
          GROUP BY r.productId 
          ORDER BY cnt DESC';
// $arr_id is populated prior to the next command and is, for example, [1,2,3,4,5]
$rt = $em->createQuery($dql2)
    ->setParameters(
        array(
            'in' => implode(',', $arr_id),
        )
    )
;
$traffic_count = $rt->getResult();

当我在MySql中运行查询时,$ rt-> getSql()显示完全相同的查询并替换?在查询中,从implode(',',$ arr_id)中回显了什么,我得到了类似的结果:

echo print_r( $traffic_count, 1);
---------------------------------
Array
(
[0] => Array
    (
        [pid] => 11234
        [cnt] => 21
    )

)

这是我在MySQL中运行的查询:

SELECT r0_.product_id AS pid, COUNT( r0_.id ) AS cnt
FROM referral_track r0_
WHERE r0_.product_id
IN ( 11234, 57, 58, 60, 61, 9677, 11216, 11217, 11239, 11296 )
GROUP BY r0_.product_id
ORDER BY cnt DESC 

并返回7个结果。我注意到getResult()似乎总是返回LAST记录,就是那里显示的数组。发生了什么事?

1 个答案:

答案 0 :(得分:1)

尝试:

$rt = $em->createQuery($dql2)
        ->setParameters(
            array(
                'in' => $arr_id,
            )
        )
    ;