sma*_*ius 4 sql doctrine dql symfony doctrine-orm
我有一个Repository类,其中包含一个调用自定义Query的方法.当我尝试findAllWithRating()从控制器内部调用时,我得到以下异常:
[2/2] QueryException: [Syntax Error] line 0, col 156: Error: Unexpected 'NULL'
Run Code Online (Sandbox Code Playgroud)
如果我尝试在phpmyadmin中调用查询,则查询效果很好!
任何的想法?
<?php
namespace Anchorbrands\Bundle\MessageBundle\Entity;
use Doctrine\ORM\EntityRepository;
class MessageRepository extends EntityRepository
{
public function findAllWithRating() {
return $this->getEntityManager()
->createQuery("SELECT id, user_id, title, slug, content, question, image_name, created_at, updated_at,
MAX(CASE WHEN rating = '1' THEN totalCount ELSE NULL END) 'Rating 1',
MAX(CASE WHEN rating = '2' THEN totalCount ELSE NULL END) 'Rating 2',
MAX(CASE WHEN rating = '3' THEN totalCount ELSE NULL END) 'Rating 3'
FROM
(
SELECT a.id, a.user_id, a.title, a.slug , a.content, a.question, a.image_name, a.created_at, a.updated_at,
rating, COUNT(*) totalCount
FROM AnchorbrandsMessageBundle:Message a
LEFT JOIN AnchorbrandsMessageBundle:Rating b
ON a.id = message_id
GROUP BY a.id, a.user_id, a.title, a.slug, a.content, a.question, a.image_name, a.created_at, a.updated_at, rating
) r
GROUP BY id, user_id, title, slug, content, question, image_name, created_at, updated_at")->getResult();
}
}
Run Code Online (Sandbox Code Playgroud)
您似乎混合了DQL和SQL.您可以在这里查看 DQL的可能性.
查看您的查询,我建议您使用SQL而不是DQL.
如何在存储库中执行SQL查询的示例:
$sql = 'SELECT * FROM table WHERE id = :id';
$params = array(
'id' => 4,
);
return $this->getEntityManager()->getConnection()->executeQuery($sql, $params)->fetchAll();
Run Code Online (Sandbox Code Playgroud)