2014-09-22 52 views
0

我有這個類:的flush()不更新嵌入文檔

class Country 
{ 
    /** 
    * @MongoDB\Id 
    */ 
    protected $id; 

    /** 
    * @MongoDB\String 
    */ 
    protected $iso; 

    /** 
    * @MongoDB\EmbedOne(targetDocument="Localstring") 
    */ 
    protected $name; 

    public function __construct(){ 
     $this->name = new Localstring(); 
    } 
} 

class Localstring 
{ 
    /** 
    * @MongoDB\Id 
    */ 
    private $id; 

    /** 
    * @MongoDB\Hash 
    */ 
    private $location = array(); 
} 

我想用一個新的翻譯更新每一個國家:

$dm = $this->get('doctrine_mongodb') 
    ->getManager(); 

foreach ($json as $iso => $name) { 
    $country = $dm->getRepository('ExampleCountryBundle:Country')->findOneByIso($iso); 

    $localstring_name = $country->getName(); 
    $localstring_name->addTranslation('es_ES', $name); 

    $dm->flush(); 
} 

如果我打印一個對象只是在沖洗前它打印正確:

Example\CountryBundle\Document\Country Object ([id:protected] => 541fe9c678f965b321241121 [iso:protected] => AF [name:protected] => Example\CountryBundle\Document\Localstring Object ([id:Example\CountryBundle\Document\Localstring:private] => 541fe9c678f965b321241122 [location:Example\CountryBundle\Document\Localstring:private] => Array ([en_EN] => Afghanistan [es_ES] => Afganistán))) 

但在數據庫上它不更新。我試圖更新$ iso,它的工作原理。爲什麼會發生?

回答

2

你忘了堅持你的對象。 flush()只需將您的更改通過persist()(在參數中用您的對象調用)註冊到DB中。它需要在這裏,因爲你不改變你的文件。你剛剛添加了翻譯。 Translatable擴展包含此功能,並且不會告訴Doctrine您的對象已被修改。當Doctrine準備查詢的變更列表時,它不會找到更改,也不會創建查詢。

您的代碼應該是這樣的:

$dm = $this->get('doctrine_mongodb') 
    ->getManager(); 

foreach ($json as $iso => $name) { 
    $country = $dm->getRepository('ExampleCountryBundle:Country')->findOneByIso($iso); 

    $localstring_name = $country->getName(); 
    $localstring_name->addTranslation('es_ES', $name); 

    $dm->persist($country); 
} 
$dm->flush(); 
+0

這些對象在數據庫中存在之前,這是一個更新的動作。 DoctrineMongoDB文檔說persist()調用它不需要(http://symfony.com/doc/current/bundles/DoctrineMongoDBBundle/index.html#updating-an-object)。無論如何,我試着用你的代碼,它不起作用。 – 2014-09-22 10:10:40

+0

正如你可以在頁面中看到的(從你的鏈接) '回想一下,這個方法只是告訴Doctrine管理或者「監視」$ product對象。您的翻譯擴展程序不管理此「觀看」。因此它不會告訴學說您的對象已更新。 – 2014-09-22 10:24:48

+0

它對你有幫助嗎? – 2014-09-22 11:00:25

0

你忘了你的持久化對象!

試試這個在您的foreach結束:$dm->persist($your_object);

和外在形式的foreach把$dm->flush();

+0

您的回答與我之前所做的答案相同。我認爲這是不好的,雙重答案;-) – 2014-09-22 10:02:04

+0

是的... 3分鐘後,對不起 – 2014-09-22 10:03:38