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

标签 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: An exception occurred while executing 'INSERT INTO country (code, label , created_at, updated_at) VALUES (?, ?, ?, ?)' with params ["EN", "England", "201 3-08-23 00:00:00", null]:

我有一个独特的学说约束

这是我的国家.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

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

最佳答案

你能持久化新实体吗?

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

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();
}

来自官方文档:

If X is a new entity instance, a new managed copy X’ will be created and the state of X is copied onto this managed instance.

所以,基本上,EntityManager::merge 可用于持久化新创建的对象并合并现有对象...

关于symfony - 使用唯一键更新实体 - 插入而不是更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20118421/

相关文章:

symfony - 如何从控制台参数设置配置参数?

php - Symfony2 - Composer 清除缓存错误

php - 如何在 Symfony 4 中使用自定义集合

php - 如何将自定义列添加到查询生成器中的选择?

symfony - 检查 Twig 模板中的类范围 ACL

symfony - 如何访问symfony配置文件中的数组?

php - FOSUserBundle 覆盖不一致

php - Symfony2 : Removing entity from middle of collection

doctrine-orm - 运行模式管理器更新时忽略 Doctrine2 实体

php - 如何使用 doctrine/symfony4 从数据库中获取(加入)两条记录