symfony doctrine QueryBuilder到数组结果
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了symfony doctrine QueryBuilder到数组结果相关的知识,希望对你有一定的参考价值。
我想从doctrine查询中获取数组。我是自我引用的实体
应用程序实体 AccessModule
/**
* @ORMManyToOne(targetEntity="AppEntityAccessModule", inversedBy="children")
* @ORMJoinColumn(name="parent_id", referencedColumnName="id", nullable=true)
*/
private $parent;
/**
* @ORMOneToMany(targetEntity="AppEntityAccessModule", mappedBy="parent", fetch="EAGER")
* @SerializerMaxDepth(2)
*/
private $children;
/**
* AccessModule constructor.
*/
public function __construct()
{
$this->children = new ArrayCollection();
}
在这个存储库中
应用程序实体 AccessModuleRepository
public function findAllArray()
{
return $this->createQueryBuilder('a')
->getQuery()
->getResult();
}
这返回带有子项和父项的对象的集合。但是当我想把这个查询作为数组->getArrayResult()
时,我得到的数组只有“id”和“name”而没有子目的“children”和“parent”。
return $ 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"
]
]
return $ 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' => []
]
]
您可以使用可选参数调用getResult方法:
return $this->createQueryBuilder('a')
->getQuery()
->getResult(Query::HYDRATE_ARRAY);
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);;
}
以上是关于symfony doctrine QueryBuilder到数组结果的主要内容,如果未能解决你的问题,请参考以下文章