使用唯一键更新实体 - 插入而不是更新

时间:2013-11-21 10:31:01

标签: symfony doctrine-orm

我的服务中有这个方法:

public function updateCountry($p_entity) {   


    var_dump($p_entity->getId());    //return 3 (as expected)
    var_dump(get_class($p_entity) ); //return Country (as expected)

    $this->em->persist($p_entity);
    $this->em->flush();
}

我叫它

$country = $em->getRepository('blabla')->find(3);
$my_service->updateCountry($country);

但生成的请求是

  

Doctrine \ DBAL \ DBALException:执行时发生异常   'INSERT INTO country(code,label,created_at,updated_at)   VALYES(?,?,?,?)'与params [“EN”,“England”,“201   3-08-23 00:00:00“,null]:

我有一个独特的学说约束

这是我的country.orm.yml

To\Bundle\Entity\Country:
    type: entity
    table: country
    repositoryClass: To\Bundle\Entity\CountryRepository

    fields:
         id:
             type: integer
             id: true
             generator:
                 strategy: AUTO
         code:
             type: string
             length: 255
             unique: true
             nullable: false

为什么我生成插入请求而不是更新

2 个答案:

答案 0 :(得分:6)

你能坚持新实体吗?

如果可以,请尝试合并您的对象:

public function updateCountry($p_entity) {
    var_dump($p_entity->getId());    //return 3 (as expected)
    var_dump(get_class($p_entity) ); //return Country (as expected)

    $this->em->merge($p_entity); // MERGE not PERSIST
    $this->em->flush();
}

来自官方文档:

  

如果X是新实体实例,则将创建新的托管副本X'   并将X的状态复制到此托管实例上。

所以,基本上,EntityManager::merge可以用来持久保存新创建的对象并合并一个对象......

答案 1 :(得分:0)

您不应该在数据库实体中保留现有数据,只能保留新实体。 因此,如果您从DB获取实体并想要更新它 你应该

  1. $实体 - >的setName()
  2. $ EM->齐平
相关问题