implementing “update if exists” in Doctrine ORM

后端 未结 4 1953
野趣味
野趣味 2020-12-10 01:46

I am trying to INSERT OR UPDATE IF EXISTS in one transaction.

in mysql, I would generally use DUPLICATE KEY (\"UPDATE ON

相关标签:
4条回答
  • 2020-12-10 01:48

    I think best way is to call entityManager->merge($entity); Because it's the closest thing to update if exist operation as promised in documentation: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/working-with-objects.html

    0 讨论(0)
  • 2020-12-10 01:52

    Doctrine supports REPLACE INTO using the replace() method. This should work exactly like the ON DUPLICATE KEY UPDATE you were looking for.

    Docs: Replacing Records

    0 讨论(0)
  • 2020-12-10 01:55

    According to https://www.vivait.co.uk/labs/updating-entities-when-an-insert-has-a-duplicate-key-in-doctrine this can be achieved with $entityManager->merge().

    $entity = new Table();
    $entity->setId(1);
    $entity->setValue('TEST');
    
    $entityManager->merge($entity);
    $entityManager->flush();
    
    0 讨论(0)
  • 2020-12-10 02:13

    The only thing I can think of is to query first for the entity if it exists otherwise create new entity.

    if(!$entity = Doctrine::getTable('Foo')->find(/*[insert id]*/))
    {
       $entity = new Foo();
    }
    /*do logic here*/
    $entity->save();
    
    0 讨论(0)
提交回复
热议问题