原则2:如果不选择至少一个根实体别名,则无法通过标识变量选择实体 [英] Doctrine2: Cannot select entity through identification variables without choosing at least one root entity alias
问题描述
我陷入了本来非常简单的学说2查询中.我有一个名为Category的实体,它与自身具有一个OneToMany关系(对于父类别和子类别).
I am stuck with an originally very simple doctrine 2 query. I have an entity called Category which has a OneToMany relation with itself (for parent and child categories).
/**
* @ORM\ManyToOne(targetEntity="Category", inversedBy="children")
*/
private $parent;
/**
* @ORM\OneToMany(targetEntity="Category", mappedBy="parent")
*/
private $children;
以下查询
$q = $this->createQueryBuilder('c')
->leftJoin('c.children', 'cc')
->select('c.name as title, cc')
->where('c.parent IS NULL');
发生错误
如果不选择至少一个根实体别名,则无法通过标识变量选择实体.
Cannot select entity through identification variables without choosing at least one root entity alias.
我真的不明白这个问题.如果我省略->select
部分,则查询确实可以工作并给出预期的结果.我已经搜索了该论坛,但找不到解决方案,该方法行得通.有人有建议吗?非常感谢.
I don't really get the issue. If I omit the ->select
part, the query does work and gives the expected result. I have already searched the forum but couldn't find a solution, that worked. Does anyone have a suggestion? Thanks a lot.
推荐答案
您的问题是,您试图从Category实体中选择一个字段,同时选择加入的Category实体的整个对象.与普通SQL不同,使用QueryBuilder组件,您不能仅从要连接的表中选择一个实体.
Your issue is that you are trying to select one field from the Category entity while simultaneously selecting the entire object of the joined Category entity. Unlike plain SQL, with the QueryBuilder component you can't select an entity only from the table you are joining on.
如果要返回包含子项的主Category对象,则可以执行->select(array('c', 'cc'))
,也可以完全省略->select()
调用.前者将在单个查询中自动选择所需的子代.如果要访问主类别实体上的子级,则后者将需要另一个SQL查询.
If you are looking to return your main Category object with the joined children, you can either do ->select(array('c', 'cc'))
, or simply omit the ->select()
call altogether. The former will automatically select the children you need in a single query. The latter will require another SQL query if you want to access children on the main Category entity.
如果出于某种原因希望您在对象中选择name
作为title
,则始终可以向实体添加另一个函数,该函数是用于检索名称的别名,而不必在查询中编写它:
If there is a reason you want name
to select as title
in your object, you can always add another function to your entity that is an alias for retrieving the name instead of having to write it in your query:
function getTitle()
{
return $this->getName();
}
这篇关于原则2:如果不选择至少一个根实体别名,则无法通过标识变量选择实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!