2013-10-24 69 views
1

在doctine中更新實體一對多關係的最佳方法是什麼? 例如:我有一個名爲booking的實體,映射到許多訪客實體。在Symfony 2/Doctrine 2中更新實體一對多關係的最佳方法

編輯預訂時,可以通過添加或刪除賓客來更改賓客人數。 目前,我計算了提交的客人人數,如果他們與當前的客人人數不同,我會刪除預訂客人並重新添加新客人!

對我來說這似乎不正確,並想知道其他人如何解決這個問題。

代碼示例:

if (count($collection)) { 
     $numberGuests = count($this->getEntity()->getGuests()); 
     foreach ($collection as $guest) { 
      if ($numberGuests != count($guests)) { 
       // delete guest if the number has changed 
       $this->getGuestManager()->delete($guest); 
      } else { 
       // update entity 
       $guest->setArrayData(Tools::getData($i, $guests)); 
      } 
     } 
    } 

回答

0

我不認爲這是一個最好的辦法,但你現在的方式是不正確的。爲什麼如果用戶修改客人,但號碼仍然相同(他從列表中刪除一個客人,但添加了一個客人)?

無論如何,我不認爲這是一個糟糕的方法來重新設置關係,每次有人編輯(也許不是最有效的),你只需要設置,從擁有方(客人),預訂。 (在多對一的關係,在「多」方必須是擁有方)

我會做,在CONTROLER:

if ($editForm->isValid()) { 

     //find all guests entities that has this booking related 
     $oldguests=$em->getRepository('YourBundle:Guest')->findby(array("booking"=>$entity)); 
     //well you will need to custom a little bit better this "findby" 

     foreach($oldguest as $guest){ 
      //remove the booking for that guest. So that guest won't have any booking linked 
      $guest->removeBooking(); 
      $em->persist($guest); 
     } 
     //now we make the link with guest and booking 
     //$form->submit($request) should have set the current entity with the current guests the user selected 
     foreach($entity->getGuests() as $currentguest){ 
      $currentguest->setBooking($entity); 
      $em->persist($guest); 
     } 

     $em->persist($entity); 
     $em->flush(); 

    } 

而且在客人實體我想補充的功能removeUser

如果你創建在做什麼控制器做GuestRepository.php的功能,並在控制器你只是調用該函數
//guest.php 
public function removeBooking(){ 
     $this->booking=NULL; 
} 

也許是更優雅。

你真的需要照顧關係的擁有方。如果您通過自己的方面允許版本,即更新預訂的客人,默認代碼app/console將不需要任何類型的定製:兩個實體都將被正確更新。

爲了簡單起見,我們可以這樣說:讓用戶更新關係的擁有方=>一切都是自動的。讓用戶更新關係=>手動定製所需的反面。 (這對多對多關係是一樣的)。

希望這會有所幫助。

+0

感謝您的評論。你說的話確實有道理!關於你的問題:爲什麼如果用戶修改客人,但號碼仍然相同(他從列表中刪除一個客人,但添加了一個新客人)? - 不,它不刪除並添加一個新的 - 它更新。如果號碼不同,它只會刪除和添加新的客人。 –

+0

隨着你的代碼 - 如果我們從客人刪除預訂 - 預訂將是多餘的。你會在重新鏈接後刪除這個嗎? –

相關問題