1

我有一个 User 实体类,具有关联的 ParticularData 实体类。通过一个表单,我想更新该 ParticularData,所以,如果我尝试从会话中获取用户:

$user = $this->getRequest()->getSession()->get('user');
$userRepository = $this->getDoctrine()->getRepository('eCommerceUserBundle:User');
$user->setParticularData($data); // $data is a ParticularData instance fetched from the form 
$userRepository->update($user);

数据库没有任何反应(尽管对于 ParticularData 已更改的系统)。然后我尝试直接从数据库中获取用户:

$userRepository = $this->getDoctrine()->getRepository('eCommerceUserBundle:User');
$user = $userRepository->selectById(20);
$user->setParticularData($data);
$userRepository->update($user);

在这种情况下,Doctrine2 将新的 ParticularData 视为一个新实例,因此它试图在 ParticularData 关联表中插入另一行(而不是更新现有的)。

我的更新方法:

public function update($user){
    $this->_em->merge($user);
    $this->_em->flush();
}

那么,我怎样才能轻松地更新关联实体告诉 Doctrine2 更新,而不是插入?

4

2 回答 2

0

我找到的解决方案是在我的 ParticularData 中做到这一点:

/**
* Converts one ParticularData in THIS ParticularData, in order to tell Doctrine2 that the    new ParticularData is the same as before; but with new fields.
* @param ParticularData $data
*/
public function cloneData($data){
    $this->setAddress($data->getAddress());
    $this->setCity($data->getCity());
    $this->setCountry($data->getCountry());
    $this->setName($data->getName());
    $this->setNIN($data->getNIN());
    $this->setPhone($data->getPhone());
    $this->setPostalCode($data->getPostalCode());
    $this->setProvince($data->getProvince());
    $this->setSurname($data->getSurname());
于 2013-09-20T15:06:16.673 回答
0

只需更新实体并调用$em->flush().

如果您在会话中存储实体,则需要合并它以告诉 ORM 必须管理该实体:

$user = $session->get('user');
$user = $em->merge($user);
于 2013-09-17T15:00:12.870 回答