dtye7921
2013-09-17 14:54
浏览 54
已采纳

更新Doctrine2中的关联实体

I have one User entity class, with an associated ParticularData enity class. Through a form, I want to update that ParticularData, so, if I try to get User from session:

$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);

Nothing happens to database (although, for the system that ParticularData HAS changed). Then I try to get User directly from database:

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

In that case, Doctrine2 treats that new ParticularData as a new instance, so it's trying to insert another Row in the ParticularData associated table (instead of updating the existing one).

My update method:

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

So, how can I update an associated entity easily telling Doctrine2 to update, not to insert?

图片转代码服务由CSDN问答提供 功能建议

我有一个User实体类,带有一个关联的ParticularData enity类。 通过表单,我想更新该ParticularData,因此,如果我尝试从会话中获取用户:</ p>

  $ user = $ this-&gt; getRequest() - &gt;  getSession() - &gt; get('user'); 
 $ userRepository = $ this-&gt; getDoctrine() - &gt; getRepository('eCommerceUserBundle:User'); 
 $ user-&gt; setParticularData($ data)  ;  // $ data是从表单
 $ userRepository-&gt; update($ user)获取的ParticularData实例; 
 </ code> </ pre> 
 
 

数据库没有任何反应(尽管如此, ParticularData已更改的系统)。 然后我尝试直接从数据库中获取用户:</ p>

  $ userRepository = $ this-&gt; getDoctrine() - &gt; getRepository('eCommerceUserBundle:User'); 
 $  user = $ userRepository-&gt; selectById(20); 
 $ user-&gt; setParticularData($ data); 
 $ userRepository-&gt; update($ user); 
 </ code> </ pre> 
  
 

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

我的更新方法:</ p>

 公共功能更新($ user){
 $ this-&gt; _em-&gt; merge($ user); 
 $ this-&gt  ; _em-&gt; flush(); 
} 
 </ code> </ pre> 
 
 

那么,如何更新关联实体,轻松告诉Doctrine2更新,而不是插入?</ p> </ div>

2条回答 默认 最新

相关推荐 更多相似问题