php - Symfony2 - 自定义存储库 + Doctrine QueryBuilder = 错误?

标签 php symfony

我在存储库中编写了自定义查询:

public function findProductDetails($filter = array(), $offset = 0, $limit = 0)
{   
    $query = $this->getEntityManager()
            ->createQuery('SELECT prod, comp, cat FROM PaulDemoBundle:Product prod JOIN prod.category cat JOIN prod.company comp WHERE prod.productName LIKE \'%'.$filter['freetext'].'%\' ');
    $query->setFirstResult($offset);
    $query->setMaxResults($limit);

    return $query->getResult();
}

现在我尝试使用 Doctrine Query Builder 的 orderBy() 部分向其中添加一个 ORDER BY:

$query->orderBy('prod.productRef', 'ASC');

但是我在尝试运行时遇到错误:

Call to undefined method Doctrine\ORM\Query::orderBy()

所以我将以下内容添加到我的存储库顶部,在 EntityRepository 的 USE 调用下方:

use Doctrine\ORM\Query;

但是,没有骰子。

我找到的所有文档都简单地显示了使用 $query->orderBy() 方法构建的查询。 Symfony2 文档中没有任何地方说明如何设置你的 repo 以使用 Doctrine Query Builder。

我究竟该如何添加 orderBy() 方法?

我是否正确构建了查询? (它基于 Symfony2 文档,但它们很差)

最佳答案

如果您不使用 queryBuilder,则不能使用应用于它的方法。您可以自己进行查询,像这样将 ORDER BY 添加到您的查询中:

->createQuery('SELECT prod, comp, cat FROM PaulDemoBundle:Product prod JOIN prod.category cat JOIN prod.company comp WHERE prod.productName LIKE \'%'.$filter['freetext'].'%\' ORDER BY prod.productRef ASC');

或者您使用 QueryBuilder 构建您的查询:

$qb = $em->createQueryBuilder();
...

参见 here对于 QueryBuilder 和 here createQuery 和 QueryBuilder 的区别。

关于php - Symfony2 - 自定义存储库 + Doctrine QueryBuilder = 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7203182/

相关文章:

php - 四舍五入到最接近的 50 美分

php - 为什么 Google 分析代码中的 PHP 代码没有正确执行?

php - 使用jquery模态形式将数据插入MYSQL

Symfony:我如何从 Controller 运行命令?

php - 表单的 View 数据应该是类 My\(...) 的实例,但它是一个 (n) 数组

php - MySQL自连接获取有序父子记录

php - 如何将字符串视为字符串而不是 PHP 中的 int

php - Doctrine2如何处理回滚后更新实体? ("The EntityManager is closed")

php - Symfony 3 - 自动序列化 DateTime 对象

Symfony2,手动分配表id值