2012-07-06 52 views
1

我正在編寫一個Symfony2應用程序,允許移動用戶通過REST服務創建和更新「Homes」。我使用MongoDB作爲存儲層和Doctrine MongoDB ODM來執行文檔處理。Doctrine Mongo ODM合併外部修改數據

GET /homes/{key}POST /homes方法工作正常。當我嘗試用PUT /homes/{key}更新現有家庭時出現問題。

下面是當前的代碼:

/** 
* PUT /homes/{key} 
* 
* Updates an existing Home. 
* 
* @param Request $request 
* @param string $key 
* @return Response 
* @throws HttpException 
*/ 
public function putHomeAction(Request $request, $key) 
{ 
    // check that the home exists 
    $home = $this->getRepository()->findOneBy(array('key' => (int) $key)); 

    // disallow create via PUT as we want to generate key ourselves 
    if (!$home) { 
     throw new HttpException(403, 'Home key: '.$key." doesn't exist, to create use POST /homes"); 
    } 

    // create object graph from JSON string 
    $updatedHome = $this->get('serializer')->deserialize(
     $request->getContent(), 'Acme\ApiBundle\Document\Home', 'json' 
    ); 

    // replace existing Home with new data 
    $dm = $this->get('doctrine.odm.mongodb.document_manager'); 
    $home = $dm->merge($updatedHome); 
    $dm->flush(); 

    $view = View::create() 
     ->setStatusCode(200) 
     ->setData($home); 

    $response = $this->get('fos_rest.view_handler')->handle($view); 
    $response->setETag(md5($response->getContent())); 
    $response->setLastModified($home->getUpdated()); 

    return $response; 
} 

傳遞到操作的JSON字符串被成功地將反序列化的JMSSerializer我的文檔對象圖,但是當我試圖合併&齊平,我得到的錯誤:

Notice: Undefined index: in ..../vendor/doctrine/mongodb-odm/lib/Doctrine/ODM/MongoDB/Mapping/ClassMetadataInfo.php line 1265 

我一直試圖在這裏遵循的文檔:http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/reference/working-with-objects.html#merging-documents

有S ^在嘗試合併之前需要對反序列化的Home做些什麼?合併錯誤的方法?

謝謝。

回答

1

我發現做到這一點的唯一方法是建立在你的文檔類的方法,所需的字段上需要更新的文件(例如,$updatedHome)作爲參數,然後只是複製到現有的文件(例如$home)。

所以上面的代碼:

// replace existing Home with new data 
$dm = $this->get('doctrine.odm.mongodb.document_manager'); 
$home = $dm->merge($updatedHome); 
$dm->flush(); 

可以替換爲:

// replace existing Home with new data 
$home->copyFromSibling($updatedHome); 
$this->getDocumentManager()->flush(); 

,然後它會工作。