主义多行组计数

时间:2013-03-13 14:54:11

标签: php count doctrine symfony-1.4 doctrine-1.2

我有以下带有学说的查询:

$q = Doctrine_Query::create()
    ->select("q.id, q.user_id, count(ua.id) as quantity")
    ->from("question q")
    ->leftJoin("q.Answers a")
    ->leftJoin("a.UserAnswers ua")
    ->groupBy("ua.user_id");

生成的SQL是:

SELECT q.id AS q__id, q.user_id AS q__user_id, COUNT(u.id) AS u__0 FROM question q LEFT JOIN answer a ON q.id = a.question_id LEFT JOIN user_answer u ON a.id = u.answer_id GROUP BY u.user_id

MySQL中的查询结果如下:

+-------+------------+------+
+ q__id + q__user_id + u__0 +
+-------+------------+------+
+     1 +          1 +    0 +
+-------+------------+------+
+    26 +          6 +    2 +
+-------+------------+------+
+    26 +          6 +    1 +
+-------+------------+------+

使用Doctrine,有一种获取“u__0”列值的方法吗?

我试过了:

$questions = $q->execute();
echo (count($questions));

但结果只有2行(不是3行)。

如何获得“u__0”列值? (0,2,1)使用Doctrine?

2 个答案:

答案 0 :(得分:2)

您必须循环每个结果并检索quantity值:

$q = Doctrine_Query::create()
    ->select("q.id as id, q.user_id as question_user_id, ua.user_id as answer_user_id, count(ua.id) as quantity")
    ->from("question q")
    ->leftJoin("q.Answers a")
    ->leftJoin("a.UserAnswers ua")
    ->groupBy("answer_user_id");

$results = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY);
foreach ($results as $result)
{
    var_dump($result['quantity']);
}

答案 1 :(得分:1)

我将SQL查询更改为:

$q = Doctrine_Query::create()
    ->select("q.id, q.user_id, a.id, count(ua.id) as quantity")
    ->from("Answer a")
    ->leftJoin("a.Question q")
    ->leftJoin("a.UserAnswers ua")
    ->groupBy("ua.user_id");

它有效;)