更新Doctrine2中的关联实体

时间:2013-09-17 14:54:48

标签: php symfony doctrine-orm

我有一个User实体类,带有一个关联的ParticularData enity类。通过表单,我想更新那个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 HAS发生变化的系统)。然后我尝试直接从数据库中获取用户:

$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更新,而不是插入?

2 个答案:

答案 0 :(得分:0)

只需更新实体并致电$em->flush()

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

$user = $session->get('user');
$user = $em->merge($user);

答案 1 :(得分: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());
相关问题