问题描述
我在查询构建器中使用以下代码来选择分数值的平均值,以及该平均值所属的类别实体:
I'm using the following code in the query builder, to select an average of score values, and the category entity to which that average belongs:
$queryBuilder = $this->createQueryBuilder('s')
->resetDQLPart('select')
->select('AVG(s.score) as score, partial c.{reviewCategoryID} as cat')
->setParameter('status', ReviewStatusType::ACCEPTED)
->join('s.review', 'r')
->join('s.category', 'c')
->where('r.campsite = :campsite')
->andWhere('r.status = :status')
->setParameter('campsite', $campsite)
->groupBy('c.reviewCategoryID');
$ campsite
是一个实体,审查属于,而分数属于审查,分数有一个类别。
$campsite
is an entity to which a review belongs, while scores belong to a review, and scores have a category.
但是当我尝试执行这个,我得到错误
But when I try to execute this, i get the error
Error: Cannot select entity through identification variables without choosing at least one root entity alias.
当我调试并检查根别名时,我看到's'被定义,应该是根实体(Score)。
When I debug and I check the root aliases, I see that 's' is defined, which is should be the root entity (Score).
任何想法可能是错的?
推荐答案
createQueryBuilder()只能从匹配实体的存储库中调用参数。如果你不从这个存储库中调用它,你应该定义一个from方法。
createQueryBuilder() can only take a parameter when it is called from the repository of the matching entity. In case you do not call it from this repository you should define a from method.
->from('YourMappingSpace:Campsite', 's')
将参数传递给createQueryBuilder()无论如何也是可以的。您可以随时手动定义它。该函数看起来像这样(只在实体存储库中):
Passing a parameter to createQueryBuilder() is for conveniance anyway. You can always define it manually. The function looks like this (Only inside the entity repository):
public function createQueryBuilder($alias)
{
return $this->_em->createQueryBuilder()
->select($alias)
->from($this->_entityName, $alias);
}
这篇关于原则:不能通过识别变量选择实体,而不选择至少一个根实体别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!