2011-03-23 38 views
0

嗨幾個小時的搜索後,我終於放棄了,我無法找到任何方式來完成這件事情,我想知道是否有可能使用PHP assiociative數組創建一個EmbedMany關係。嵌入式文檔和php專用數組,如何在MongoDB中使用教條?

我可以使用@field(type =「hash」),但是不能將嵌入式文檔添加到該鍵!

下面是代碼我現在有:

<?php 

namespace Entity; 

/** 
* @Document(collection="object_types") 
*/ 
class OType 
{ 
    /** 
    * @Id 
    * @var integer 
    */ 
    private $id; 

    /** 
    * @Field(type="string") 
    * @var string 
    */ 
    private $name; 

    /** 
    * @EmbedMany(targetDocument="Property") 
    */ 
    private $properties = array(); 

    /** 
    * Node Type 
    * 
    * @param string $name 
    */ 
    public function __construct($name) 
    { 
     $this->name = $name; 


    } 

    /** 
    * Set name 
    * 
    * @param string $name 
    * @return void 
    */ 
    public function setName($name) 
    { 
     $this->name = $name; 
    } 

    /** 
    * Get name 
    * 
    * @return string 
    */ 
    public function getName() 
    { 
     return $this->name; 
    } 

    /** 
    * Add property 
    * 
    * @param Property $property 
    */ 
    public function addProperty(Property $property) 
    { 
     $this->properties[$property->getName()] = $property; 
    } 

    /** 
    * Get properties 
    * 
    * @return Property[] 
    */ 
    public function getProperties() 
    { 
     return $this->properties; 
    } 
} 

我想要做這樣的事情:

$property = new Property(); 
$property->setName('memberof'); 
$property->setType('string'); 

$type = new OType(); 
$type->setName('user'); 
$type->addProperty($property); 

而得到這樣的結果:

{ 
    "_id": { 
    "$oid": "4d89ae2c2eea0f8406000004" 
    }, 
    "name": "user", 
    "properties": [ 
    "memberof": { 
     "name": "memberof", 
     "type": "string" 
    } 
    ] 
} 

感謝您的幫助。

問候 Flamur

回答

0

你不應該這樣做(只要堅持這樣做的一個辦法:或者你總是使用關聯數組,或使用嵌入文檔)

然而,這一招可以幫助:

只需將您的屬性數組中的值轉換爲Property對象即可。

//Add to your document: 
/** @PostLoad */ 
public function postLoad() 
{ 
    foreach($this->properties as $k => $p) { 
     if(is_array($p)) { 
      $newP = new Property(); 
      $newP = $p['name']; 
      //.. 
      $this->properties[$k] = $newP; 
     } 
    } 
} 
相關問題