2013-09-17 14:54
浏览 54


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 

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

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){

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

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

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

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

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

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



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


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanlumei5941 2013-09-20 15:06

    The solution I found was to do that in my 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){
    点赞 打赏 评论
  • doushajian2018 2013-09-17 15:00

    Just update the entity and call $em->flush().

    If you're storing an entity in a session, you need to merge it to tell the ORM that the entity must be managed:

    $user = $session->get('user');
    $user = $em->merge($user);
    点赞 打赏 评论

相关推荐 更多相似问题