在我的“主题”实体中,我有一个一对多、自引用的关系$parent:$children
。
class Topic
{
/** @ORM\Id
* @Column(type="integer")
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/** @Column(length=40, unique=true) */
private $name;
/**
* @ORM\ManyToOne(targetEntity="Topic", inversedBy="children")
*/
private $parent;
/**
* @ORM\OneToMany(targetEntity="Topic", mappedBy="parent")
*/
private $children;
}
我可以加入表格来获得这样的父子层次结构:
return $this->getEntityManager()->createQuery('
SELECT t, c FROM My\xxxBundle\Entity\Topic t
LEFT JOIN t.children c
WHERE t.parent IS NULL
')
->getArrayResult();
这是正确的输出:
array
0 =>
array
'id' => int 1
'name' => string 'Parent 1'
'slug' => string 'p-1'
'description' => null
'children' =>
array
0 =>
array
'id' => int 2
'name' => string 'Child 1-1'
'slug' => string 'c-1-1'
'description' => null
1 =>
array
'id' => int 3
'name' => string 'Child 1-2'
'slug' => string 'c-1-2'
'description' => null
1 =>
array
'id' => int 4
'name' => string 'Parent 2'
'slug' => string 'p-2'
'description' => null
'children' =>
array
empty
...
但如果我尝试获取 SELECT 语句中的特定列:
SELECT t.name, c.name FROM My\xxxBundle\Entity\Topic t
我得到一个子实体的平面数组,即只有c.name
. 如果父母没有孩子,我只会得到一个空值作为它的名字:
1 =>
array (size=1)
'name' => string 'Child 1-1' (length=14)
2 =>
array (size=1)
'name' => string 'Child 1-2' (length=14)
3 =>
array (size=1)
'name' => null
4 =>
array (size=1)
'name' => string 'Child 3-1' (length=5)
根据 Mark 的建议,我重命名了子实体的名称字段:
SELECT t.name, c.name AS child_name FROM My\xxxBundle\Entity\Topic t
但我仍然得到错误的格式:
array
0 =>
array
'name' => string 'Parent 1'
'child_name' => string 'Child 1-1'
1 =>
array
'name' => string 'Parent 1'
'child_name' => string 'Child 1-2'
2 =>
array
'name' => string 'Parent 2'
'child_name' => string 'Child 2-1'