5 doctrine mongodb 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;
}
}
...
Run Code Online (Sandbox Code Playgroud)
我需要一个完整的嵌入式集合数组来输出整个数据并通过json进行渲染.我的查询如下所示:
$query = $this->_dbContainer->getDocumentManager()->createQueryBuilder('User')->field('deletedAt')->exists(false);
$result = $query->field('id')->equals($id)->getQuery()->getSingleResult();
Run Code Online (Sandbox Code Playgroud)
例如,如果我toArray()像这样调用函数:
$array = $result->getSubscription()->toArray();
print_r($array);
Run Code Online (Sandbox Code Playgroud)
那么输出只是顶层的一个数组:
[0] => Object Subscription...
[1] => Object Subscription...
...
Run Code Online (Sandbox Code Playgroud)
我怎样才能轻松获得这样的数组?
[0] => array('subscriptionLabel' => 'value1', 'field' => 'value1', ...)
[1] => array('subscriptionLabel' => 'value2', 'field' => 'value2', ...)
...
Run Code Online (Sandbox Code Playgroud)
是否有任何最佳实践或可能缺少帮助脚本来防止像这样的代码丑陋(如何处理孩子 - >孩子 - >孩子szenarios?丑陋 - >丑陋丑陋 - >丑丑丑陋 - > ...):
$example = array();
foreach($result->getSubscription() as $key => $subscription) {
$example[$key]['subscriptionLabel'] = $subscription->getSubscriptionLabel();
$example[$key]['field'] = $subscription->getField();
...
}
Run Code Online (Sandbox Code Playgroud)
非常感谢,斯蒂芬
小智 12
该死的简单回答!只需使用 - >水合物(假)就完成了.
对于查找查询,默认情况下结果是水合的,您可以返回文档对象而不是数组.你可以通过使用hydrate(false)方法禁用它并直接从mongo获取原始结果:
<?php
$users = $dm->createQueryBuilder('User')
->hydrate(false)
->getQuery()
->execute();
print_r($users);
Run Code Online (Sandbox Code Playgroud)