【问题标题】:Symfony2 Using Query in Custom Repository ClassSymfony2 在自定义存储库类中使用查询
【发布时间】:2013-01-02 05:21:16
【问题描述】:

我有一个带有调用自定义查询方法的存储库类。当我尝试从控制器内部调用 findAllWithRating() 时,出现以下异常:

[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();
    }

}

【问题讨论】:

    标签: sql symfony doctrine doctrine-orm dql


    【解决方案1】:

    您似乎混合使用了 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();
    

    【讨论】:

    • 我正在使用它,就像这里描述的那样:symfony.com/doc/current/book/… 关键是我不能使用原始 sql,因为在这种情况下,学说不会映射属性。
    • 我们可以使用bind的参数吗?
    猜你喜欢
    • 2013-02-17
    • 1970-01-01
    • 2016-08-29
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    相关资源
    最近更新 更多