mongodb - Doctrine ODM (MongoDB) - 获取对象的完整数组?

标签 mongodb doctrine doctrine-orm

在接收我的文档的完整数组(包含嵌入子集合的所有数据和对象)时遇到问题。我的文档看起来和这个一模一样:

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/

相关文章:

mongodb - java.lang.NoSuchMethodError : com. mongodb.client.MongoCollection.insertOne 将条目插入到 Javers Mongodb 集合时出现异常

php - Doctrine2 oneToOne 复合主键不可为空

php - Symfony2 Doctrine 查询

doctrine-orm - 如何将 silex 与 Doctrine orm EntityManager 一起使用?

php - 如何在不加入 doctrine2 的情况下获得 id?

javascript - 从 Meteor 服务器插入数据库不起作用

php - 特定汉字在 http get 请求期间被错误编码

java - Bungeecord 玩家传输上的 Mongo 数据库配置文件同步

php - Doctrine 2 如何在不调用实体构造函数的情况下检索实体?

php - 如何用教义随机选择