在接收我的文档的完整数组(包含嵌入子集合的所有数据和对象)时遇到问题。我的文档看起来和这个一模一样:
use Doctrine\Common\Collections\ArrayCollection;
/** @Document(collection="user") */
class User {
/** @Id */
protected $id;
/** @String */
protected $firstname;
/** @String */
protected $lastname;
/** @EmbedMany(targetDocument="Email") */
protected $email;
/** @EmbedMany(targetDocument="Address") */
protected $address;
/** @EmbedMany(targetDocument="Subscription") */
protected $subscription;
/**
* Construct the user
*
* @param array $properties
* @throws User_Exception
*/
public function __construct(array $properties = array()) {
$this->email = new ArrayCollection();
$this->address = new ArrayCollection();
$this->subscription = new ArrayCollection();
foreach($properties as $name => $value){
$this->{$name} = $value;
}
}
...
我需要一个完整的嵌入式集合数组来输出整个数据并通过json渲染。我的查询如下所示:
$query = $this->_dbContainer->getDocumentManager()->createQueryBuilder('User')->field('deletedAt')->exists(false);
$result = $query->field('id')->equals($id)->getQuery()->getSingleResult();
例如,如果我像这样调用 toArray()
函数:
$array = $result->getSubscription()->toArray();
print_r($array);
那么输出只是顶层的一个数组:
[0] => Object Subscription...
[1] => Object Subscription...
...
我怎样才能轻松获得这样的数组?
[0] => array('subscriptionLabel' => 'value1', 'field' => 'value1', ...)
[1] => array('subscriptionLabel' => 'value2', 'field' => 'value2', ...)
...
是否有任何最佳实践或可能缺少一些帮助脚本来防止像这段代码这样丑陋的事情(如何处理 child -> child -> child 的场景?丑陋 -> 丑陋的丑陋 -> 丑陋的丑陋 -> ...) :
$example = array();
foreach($result->getSubscription() as $key => $subscription) {
$example[$key]['subscriptionLabel'] = $subscription->getSubscriptionLabel();
$example[$key]['field'] = $subscription->getField();
...
}
非常感谢, 斯蒂芬
最佳答案
该死的简单答案!只需使用 ->hydrate(false) 就可以了。
For find queries the results by default are hydrated and you get document objects back instead of arrays. You can disable this and get the raw results directly back from mongo by using the hydrate(false) method:
<?php
$users = $dm->createQueryBuilder('User')
->hydrate(false)
->getQuery()
->execute();
print_r($users);
关于mongodb - Doctrine ODM (MongoDB) - 获取对象的完整数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6155189/