flush()不会更新嵌入文档

时间:2014-09-22 09:50:25

标签: mongodb symfony doctrine-orm embed 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 个答案:

答案 0 :(得分:2)

你忘了坚持你的对象。 flush()只是将您persist()注册的更改推送到DB(在参数中使用您的对象调用)。它需要在这里,因为您不会更改您的文档。你刚刚添加了翻译。可转换扩展涵盖此功能,并不告诉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();

答案 1 :(得分:0)

你忘记了坚持你的对象!

在你的foreach结束时尝试这个:$dm->persist($your_object);

和外部形式foreach放$dm->flush();