2017-10-06 36 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调用。 –