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


基础教程推荐
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01