2013-01-18 77 views
4

我有一個帶有調用自定義查詢的方法的存儲庫類。當我嘗試調用findAllWithRating()從控制器內我得到了以下異常:Symfony2在自定義存儲庫類中使用查詢

[2/2] QueryException: [Syntax Error] line 0, col 156: Error: Unexpected 'NULL' 

如果我打電話的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(); 
    } 

} 

回答

8

您似乎混合了DQL和SQL。 你可以看看DQL here有什麼可能。

看着你的查詢,我建議你使用SQL而不是DQL。

如何做一個倉庫內的SQL查詢的一個例子:

$sql = 'SELECT * FROM table WHERE id = :id'; 
$params = array(
    'id' => 4, 
); 

return $this->getEntityManager()->getConnection()->executeQuery($sql, $params)->fetchAll(); 
+0

我使用它喜歡它在這裏描述:http://symfony.com/doc/current/book/doctrine.html #查詢對象與DQL 重點是,我不能使用原始的SQL原因教義不會映射propierties在這種情況下。 – smartius

+0

我們可以使用'bind'來使用參數嗎? – Developer