这个问题是我提出的问题的后续问题(并收到了有效的答复)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/