我想从doctrine查询中获取数组。 我是自引用实体
应用\实体\ AccessModule
/**
* @ORM\ManyToOne(targetEntity="App\Entity\AccessModule", inversedBy="children")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id", nullable=true)
*/
private $parent;
/**
* @ORM\OneToMany(targetEntity="App\Entity\AccessModule", mappedBy="parent", fetch="EAGER")
* @Serializer\MaxDepth(2)
*/
private $children;
/**
* AccessModule constructor.
*/
public function __construct()
{
$this->children = new ArrayCollection();
}
在此存储库中
应用\实体\ AccessModuleRepository
public function findAllArray()
{
return $this->createQueryBuilder('a')
->getQuery()
->getResult();
}
这返回包含子项和父项的对象的集合。但是,当我想将此查询作为数组->getArrayResult()
时,我只使用" id"和"名称"没有子女"孩子"和"父母"。
返回$ this-> createQueryBuilder(' a') - > getQuery() - > getArrayResult();
array:3 [▼
0 => array:2 [▼
"id" => 2
"name" => "Common module"
]
1 => array:2 [▼
"id" => 3
"name" => "User Module"
]
2 => array:2 [▼
"id" => 4
"name" => "Admin Module"
]
]
返回$ this-> createQueryBuilder(' a') - > getQuery() - > getResult();
array:3 [▼
0 => AccessModule {#5118 ▼
-id: 2
-name: "Common module"
-parent: null
-children: PersistentCollection {#5208 ▼
-snapshot: array:2 [ …2]
-owner: AccessModule {#5118}
-association: array:15 [ …15]
-em: EntityManager {#2624 …11}
-backRefFieldName: "parent"
-typeClass: ClassMetadata {#3093 …}
-isDirty: false
#collection: ArrayCollection {#5209 ▼
-elements: array:2 [▼
0 => AccessModule {#5325 ▼
-id: 3
-name: "User Module"
-parent: AccessModule {#5118}
-children: PersistentCollection {#5327 ▶}
}
1 => AccessModule {#5328 ▼
-id: 4
-name: "Admin Module"
-parent: AccessModule {#5118}
-children: PersistentCollection {#5330 ▶}
}
]
}
#initialized: true
}
}
1 => AccessModule {#5325 ▶}
2 => AccessModule {#5328 ▶}
]
如何使用引用对象从getResult()获取数组?
预期结果
[
[0] => [
'id' => 1,
'name' => 'Common Module',
'parent' => null,
'children => [
[0] => [
'id' => 2,
'name' => 'User Module',
'parent' => 1,
'children' => []
],
[1] => [
'id' => 3,
'name' => 'Admin Module',
'parent' => 1,
'children' => []
]
]
],
[1] => [
'id' => 2,
'name' => 'User Module',
'parent' => 1,
'children' => []
],
[2] => [
'id' => 3,
'name' => 'Admin Module',
'parent' => 1,
'children' => []
]
]
答案 0 :(得分:0)
您可以使用可选参数调用getResult方法:
return $this->createQueryBuilder('a')
->getQuery()
->getResult(Query::HYDRATE_ARRAY);
答案 1 :(得分:0)
Doctrine Array层次结构
如果您希望将嵌套集层次结构水合成数组而不是对象,则可以使用HYDRATE_ARRAY_HIERARCHY
常量来实现。它与HYDRATE_RECORD_HIERARCHY
相同,只是它使用PHP数组而不是对象。
http://doctrine.readthedocs.io/en/latest/en/manual/data-hydrators.html#nested-set-array-hierarchy
public function findAllArray()
{
return $this->createQueryBuilder('a')
->getQuery()
->execute(array(), Doctrine_Core::HYDRATE_ARRAY_HIERARCHY);;
}