2014-12-03 28 views
0

我使用的是自定義的FindBy過濾器,我想通過排序依據和orderDirection像這樣的參數查詢錯誤:Symfony的 - 創建

public function findByFilter($filter, $orderBy = null, $orderDirection = null) 
{ 
... 

return $this->getEntityManager()->createQuery(
     'SELECT i FROM ' . $entityName . ' i ' . 
     'WHERE i.id LIKE :id' 
     . ($orderBy) ? ' ORDER BY i.' . $orderBy : '' 
     . ($orderDirection) ? ' ' . $orderDirection : '' 
    ) 
     ->setParameter('id', $filter) 
     ->getResult() 
    ; 
} 

我收到以下錯誤消息:

[Syntax Error] line 0, col 1: Error: Expected SELECT, UPDATE or DELETE, got 'ASC'

回答

2

試試這個:

return $this->getEntityManager()->createQuery(
     'SELECT i FROM ' . $entityName . ' i ' . 
     'WHERE i.id LIKE :id ' 
     . ($orderBy ? ' ORDER BY i.' . $orderBy : '') 
     . ($orderDirection ? ' ' . $orderDirection : '') 
    ) 
     ->setParameter('id', $filter) 
     ->getResult() 
    ; 
} 

你被... :id和合作後缺少空間完整的三元操作符必須位於括號內。 也有一個排序依據的方法:

public function findByFilter($filter, $orderBy = null, $orderDirection = null) 
{ 
    ... 

    $query = $this->getEntityManager()->createQuery($entityName . ' i') 
     ->where('i.id LIKE :id') 
     ->setParameter('id', $filter); 

    if ($orderBy && $orderDirection) { 
     $query->orderBy('i.' . $orderBy . ' ' . $orderDirection); 
    } 
    return $query->getResult(); 
} 

代碼未經測試,但應該以某種方式以這種方式工作。更多信息:https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/EntityManager.php#L287https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Query.php

UPDATE:好抱歉,我想通了,有當然的查詢和QueryBuilder的略有區別。查詢似乎缺少orderBy方法。

+0

你的回答需要一些改變,但它幫助我解決了它。我會接受它作爲正確的答案。查詢應該像這樣:$ query = $ this - > _ em-> getRepository($ entityName) - > createQueryBuilder('i')和其他所有內容都是您的第二部分答案。謝謝 – 2014-12-03 11:00:08