沃梦达 / 编程问答 / php问题 / 正文

Doctrine2:不能通过标识变量选择实体而不选择至少一个根实体别名

Doctrine2: Cannot select entity through identification variables without choosing at least one root entity alias(Doctrine2:不能通过标识变量选择实体而不选择至少一个根实体别名)

本文介绍了Doctrine2:不能通过标识变量选择实体而不选择至少一个根实体别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被一个最初非常简单的学说 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).

/**
 * @ORMManyToOne(targetEntity="Category", inversedBy="children")
 */
private $parent;

/**
 * @ORMOneToMany(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();
}

这篇关于Doctrine2:不能通过标识变量选择实体而不选择至少一个根实体别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Doctrine2:不能通过标识变量选择实体而不选择至少一个根实体别名

基础教程推荐