使用唯一键更新实体 - 插入而不是更新 [英] Update an Entity with Unique Key - Insert instead of update
问题描述
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)
VALUES(?,?,?,?)时发生异常'with params [EN,England,201
3-08-23 00:00:00,null]:
我有一个独特的教义约束
这是我的country.orm.yml
To\Bundle\Entity\Country:
type:entity
表:country
repositoryClass:To\Bundle\Entity\CountryRepository
字段:
id:
类型:整数
id:true
生成器:
策略:AUTO
代码:
type:string
length:255
unique:true
可空: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();
}
从官方文档:
如果X是一个新的实体实例,将创建一个新的托管副本X'
,并将X的状态复制到该托管实例上。
所以,基本上, EntityManager :: merge
可以用来同时保留新创建的对象并合并一个...
I have this method in my service:
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();
}
I call it by
$country = $em->getRepository('blabla')->find(3);
$my_service->updateCountry($country);
But the request generated is
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]:
I have a unique doctrine constraint
this is my 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
Why have I an insert request generated instead of the update one?
Can you persist new entity at all?
If you can, try merging your object instead:
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();
}
From official docs:
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.
So, basically, EntityManager::merge
can be used to both persist newly created object and merge exsistent one...
这篇关于使用唯一键更新实体 - 插入而不是更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!