php 在 Doctrine ORM 中实现“如果存在则更新”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1132571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
implementing "update if exists" in Doctrine ORM
提问by seans
I am trying to INSERT OR UPDATE IF EXISTSin one transaction.
我试图INSERT OR UPDATE IF EXISTS在一笔交易中。
in mysql, I would generally use DUPLICATE KEY("UPDATE ON DUPLICATE KEY".) I'm aware of many solutions to this problem using various SQL variants and sub-queries, but I'm trying to implement this in Doctrine (PHP ORM). It seems there would be Doctrine methods for doing this since it's so feature packed, but I'm not finding anything. Is this sort of thing a problem using PHP ORM packages for some reason? Or do any Doctrine experts know how to achieve this through hacks or any means?
在mysql 中,我通常会使用DUPLICATE KEY("UPDATE ON DUPLICATE KEY".) 我知道使用各种 SQL 变体和子查询来解决这个问题的许多解决方案,但我试图在 Doctrine (PHP ORM) 中实现它。似乎会有 Doctrine 方法来执行此操作,因为它的功能非常丰富,但我什么也没找到。出于某种原因,使用 PHP ORM 包会出现这种问题吗?或者是否有任何 Doctrine 专家知道如何通过黑客或任何方式实现这一目标?
回答by Bj?rn Tantau
According to https://www.vivait.co.uk/labs/updating-entities-when-an-insert-has-a-duplicate-key-in-doctrinethis can be achieved with $entityManager->merge().
根据https://www.vivait.co.uk/labs/updating-entities-when-an-insert-has-a-duplicate-key-in-doctrine这可以通过$entityManager->merge().
$entity = new Table();
$entity->setId(1);
$entity->setValue('TEST');
$entityManager->merge($entity);
$entityManager->flush();
回答by ken
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();
回答by pix0r
Doctrine supports REPLACE INTOusing the replace()method. This should work exactly like the ON DUPLICATE KEY UPDATEyou were looking for.
Doctrine 支持REPLACE INTO使用该replace()方法。这应该与ON DUPLICATE KEY UPDATE您正在寻找的完全一样。
Docs: Replacing Records
文档:替换记录
回答by Javlonbek
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
我认为最好的方法是调用 entityManager->merge($entity); 因为如果按照文档中承诺的存在操作,它是最接近更新的东西:https: //www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/working-with-objects.html

