3

这个问题是我在此处提出的问题(并收到了有效的答案)的后续问题。

我怎样才能把它翻译成 DQL?JOINs 上的文档让我有点困惑。


编辑:

我将 Doctrine 与 Symfony2 一起使用,并具有以下实体:

问题:

/**
 * @ORM\Entity
 * @ORM\Table(name="Question", indexes={@ORM\Index(name="id_idx", columns={"id"})})
 */

class Question
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string question
     *
     * @ORM\Column(name="question", type="string", length=255)
     */
    private $question;

    /**
     * @var array scores
     *
     * @ORM\OneToMany(targetEntity="Score", mappedBy="question")
     */
    private $scores;

    // getters and setters
}

分数:

/**
 * @ORM\Entity
 * @ORM\Table(name="Score", indexes={@ORM\Index(name="id_idx", columns={"id"})})
 */

class Score
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var integer $question
     *
     * @ORM\ManyToOne(targetEntity="Question", inversedBy="scores")
     * @ORM\JoinColumn(name="question_id", referencedColumnName="id")
     */
    private $question;

    /**
     * @var float score
     *
     * @ORM\Column(name="score", type="float")
     */
    private $score;

    // getters and setters
}

我使用了以下查询:

$query = $em->createQuery('SELECT q AS question, AVG(s.score) AS average FROM CMSBundle:Question q JOIN q.scores s GROUP BY q.id ORDER BY q.id ASC');

$questions = $query->getResult();

但是,对于该查询,$questions 包含 0 个元素。我也没有收到任何错误(至少,PhpStorm 在其调试器中找不到任何错误)。

由于缺乏关于为什么我从我的查询中几乎没有得到任何反馈的反馈,我有点不知所措。任何帮助,将不胜感激。

4

1 回答 1

1

我记得上周刚遇到这个问题。我花了很长时间弄清楚如何做到这一点,并设法提出了以下 DQL。向您的问题的存储库类添加一个新方法。

我不得不调整自己的代码以匹配问题,所以不能保证它可以工作,但试一试。

<?php

namespace Acme\CMSBundle\Entity;

use Doctrine\ORM\EntityRepository;

class QuestionRepository extends EntityRepository
{
    /**
     * @return array
     */
    public function findAverageScoresPerQuestion()
    {
        $dql = <<<SQL
SELECT
    q question,
    AVG(s.score) average
FROM
    Acme\CMSBundle\Entity\Question q,
    Acme\CMSBundle\Entity\Score s
WHERE
    s.question = q.id
GROUP BY q.id
ORDER BY q.id ASC
SQL;

        $q = $this->_em->createQuery($dql);

        return $q->getResult();
    }
}

从控制器使用 Twig 渲染结果时,question属性嵌套更深一层

public function averageScoresAction()
{
    $em = $this->getDoctrine()->getManager();
    $questions = $em->getRepository('AcmeCMSBundle:Question')->findAverageScoresPerQuestion();

    return $this->render('AcmeCMSBundle:Question:questions.html.twig', array(
        'questions' => $questions
    ));
}

questions.html.twig

  <table>
    <thead>
      <tr>
        <th>Question
        <th>Average Score
      </tr>
    </thead>
    <tbody>
    {% for q in questions %}
      <tr>
        <td>{{ q.question.question }}
        <td>{{ q.average }}
      </tr>
    {% else %}
      <tr>
        <td colspan="2">No results found
      </tr>
    {% endfor %}
    </tbody>
  </table>
于 2013-06-08T15:18:25.897 回答