[英]Restore document with embedded documents on ODM
這里有兩個示例類:
/** @ODM\Document */
class Product implements JsonSerializable{
/** @ODM\String */
protected $some_property;
/** @ODM\EmbedMany */
protected $attributes;
public function jsonSerialize(){
$o = new StdClass();
$o->property = $this->some_property;
$o->attributes = $this->attributes;
return $o;
}
}
/** @ODM\EmbeddedDocument */
class Attribute implements JsonSerializable{
/** @ODM\String */
protected $some_property;
public function jsonSerialize(){
$o = new StdClass();
$o->property = $this->some_property;
return $o;
}
}
在我的代碼中,我創建一個Product實例,然后一些進程在$product->attributes
上創建Attribute實例數組。 我使用Doctrine ODM將Product實例持久地存入mongoDB中。 我可以進入數據庫(使用rockmongo),然后看到已有的文檔以及JSON視圖上對attributes
數組類的注釋:
"_doctrine_class_name": "\Attribute"
但是,當我使用QueryBuilder查詢該產品時,我沒有獲得Attribute實例數組,而是得到了PersistentCollection(在運行時查看調試器的外觀)。
我相信這與延遲加載有關 ,但它破壞了我的代碼。 當我嘗試調用json_encode($product)
,而不是級聯到每個Attribtue
實例,它只是返回一個空數組。
這是我期望從json_encode()獲得的內容:
{
"property": "some product value",
"attributes": [
{
"property": "some attribute value"
},
{
"property": "some attribute value"
}
]
}
有什么方法可以禁用延遲加載 ,或強制每個Attribute實例正確地實例化嗎? 還是通過其他任何方式都可以獲取所需的JSON對象,而不必手動遍歷整個結構? 謝謝!
我如何最終解決延遲加載的問題:
// parent jsonSerialize method
public function jsonSerialize(){
$o = new StdClass();
$o->property = $this->some_property;
$a = [];
foreach($this->attributes as $attr){
$a[] = $attr;
}
$o->attributes = $a;
return $o;
}
這迫使PersistentCollection對象將適當的實例一一吐出來,然后jsonSerializable方法可以很好地級聯響應。
IMO丑陋,但解決了這個問題。 可悲的是,您必須將此方法應用於您擁有的每個嵌入式對象依賴項。
孔有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.