Hi, I have some complex MySQL queries which would be hard to turn into DQL.
Is it possible to run raw sql queries using Doctrine 2? If so, how?
I googled alot about this issue and could only find the solution for Doctrine 1.2.
Moderators: dcobalt, tiagojsag
public function foobar($foobar)
{
$stmt = $this->getEntityManager()
->getConnection()
->prepare('SELECT COUNT(id) AS num, foo FROM bar WHERE foobar = :foobar GROUP BY foo');
$stmt->bindValue('foobar ', $foobar);
$stmt->execute();
return $stmt->fetchAll();
}
$rsm = new ResultSetMapping;
$rsm->addScalarResult('optionname', 'option');
$rsm->addScalarResult('answers', 'count');
return $this->_em->createNativeQuery('
SELECT
qo.title as optionname,
COUNT(qap.answer_id) as answers
FROM
quiz_answer_option qap
INNER JOIN quizoption qo ON qo.id = qap.option_id
INNER JOIN quizquestion qq ON qq.id = qo.quizquestion_id
WHERE
qq.active
AND qq.id = :quizquestionid
GROUP BY qap.option_id
ORDER BY qo.number asc
', $rsm)
->setParameter('quizquestionid', $quizquestion->getId())
->getResult();althaus wrote:You can do simple stuff like this:
- Code: Select all
public function foobar($foobar)
{
$stmt = $this->getEntityManager()
->getConnection()
->prepare('SELECT COUNT(id) AS num, foo FROM bar WHERE foobar = :foobar GROUP BY foo');
$stmt->bindValue('foobar ', $foobar);
$stmt->execute();
return $stmt->fetchAll();
}
This is some code I use in a custom EntityRepository, but you can do it anywhere you get access to the EM.
Cheers
Matthias
althaus wrote:Perhaps I'll setup a blog to collect a lot of common use cases.
Return to General Symfony 2 discussion
Users browsing this forum: No registered users and 5 guests