我的服务中有这个方法:
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/