mysql - 将 MySQL 查询转换为 DQL

标签 mysql doctrine-orm dql

这个问题是我提出的问题的后续问题(并收到了有效的答复)here .

如何将其转换为 DQL? JOIN 上的文档让我有点困惑。


编辑:

我在 Symfony2 中使用 Doctrine,并且有以下实体:

问题:

/**
 * @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 无法在其调试器中找到任何错误)。

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

最佳答案

我记得就在上周遇到了这个问题。我花了很长时间弄清楚如何做到这一点,并设法提出了以下 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();
    }
}

当从 Controller 使用 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>

关于mysql - 将 MySQL 查询转换为 DQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16899040/

相关文章:

php - MySQL 报告一个主键但不能从表中删除它

mysql - Doctrine2 MariaDB 集成

php - 是否可以为 JoinColumn 引用 'id' 以外的列?

symfony - Doctrine2 "order by"在 "group by"之前

doctrine-orm - 这是使用 Doctrine2 的 WHERE IN 表达式处理有序数组的正确方法吗?

php - Spry 选项卡式面板不显示动态数据

java - 如何将 2 个 json 合并为一个来解析 JSON

python - 当 mysql 和用户输入不相同时,标签提供错误的动态名称

symfony - 如何在 FormType 中使用 Repository 自定义函数

php - 使用 SUM(a.id=1) 作为 `ìdentifier` 时的学说错误:预期的学说\ORM\查询\Lexer::T_CLOSE_PARENTHESIS,得到 '='