2017-10-06 34 views
1

我在做什麼錯:DQL定製回購內部

public function findAllVendorsByCategory ($categoryId) 
{ 
    $em = $this->getEntityManager(); 

    $vendors = $em->createQueryBuilder('v') 
     ->distinct() 
     ->innerJoin('v.category', 'c') 
     ->where('c.id = :category_id') 
     ->setParameter('category_id', $categoryId) 
     ->getQuery() 
     ->iterate() 
    ; 

    return $vendors; 
} 

我特別正的錯誤是:

No alias was set before invoking getRootAlias().

我已經嘗試添加選擇(),並沒有什麼工作 - 這個代碼工作在控制器的上下文中創建時很好 - 但是當我將它移動到它自己的repo時 - poof!?!

想法?

編輯|最新嘗試

$vendors = $em->createQueryBuilder() 
     ->distinct() 
     ->from('Vendor', 'v') 
     ->innerJoin('category', 'c', JOIN::ON, 'v.category_id = c.id') 
     ->where('c.id = :category_id') 
     ->setParameter('category_id', $categoryId) 
     ->getQuery() 
     ->iterate() 
    ; 

這將產生DQL,如:

SELECT DISTINCT FROM Vendor v INNER JOIN category c ON v.category_id = c.id WHERE c.id = :category_id 

但是,當我在斌/控制檯或通過應用評估DQL我得到:

[Syntax Error] line 0, col 16: Error: Expected IdentificationVariable | ScalarExpression | AggregateExpression | FunctionDeclaration | PartialObjectExpression | "(" Subselect ")" | CaseExpression, got 'FROM'

+0

你有沒有在你的實體的'@Entity()'註釋中註冊repositoryClass? – dbrumann

+0

在存儲庫中使用'$ this-> createQueryBuilder'(例如存儲庫中的方法),或者在使用EntityManager版本時使用' - > from(...)'添加要選擇的實體/表格'createQueryBuilder'。 – ccKep

+0

選擇整個實體時,groupBy是要走的路 - 只能選擇不同的標量值。你的查詢有什麼獨特之處?我想你的ID是獨一無二的? – ccKep

回答

3

你應該使用createQueryBuilder方法從存儲庫,如果您繼承Doctrine\ORM\EntityRepository

從原則EntityRepository類別名方法:

/** 
* Creates a new QueryBuilder instance that is prepopulated for this entity name. 
* 
* @param string $alias 
* @param string $indexBy The index for the from. 
* 
* @return QueryBuilder 
*/ 
public function createQueryBuilder($alias, $indexBy = null) 
{ 
    return $this->_em->createQueryBuilder() 
     ->select($alias) 
     ->from($this->_entityName, $alias, $indexBy); 
} 

所以:

$vendors = $this->createQueryBuilder('v') 
    ->distinct() 
    ->innerJoin('v.category', 'c') 
    ->where('c.id = :category_id') 
    ->setParameter('category_id', $categoryId) 
    ->getQuery() 
    ->iterate() 
; 

或者,您可以繼續使用從EntityManager的的createQueryBuilder方法,但是你需要添加至少應->from調用(如別名方法)。

+0

我認爲Symfony/Doctrine是如何在幕後處理回購的?在這一點上,我寧願正確的DQL調用。 –