簡體   English   中英

在 Symfony 2 / Doctrine 2 中更新實體一對多關系的最佳方法

[英]Best way to update entity one to many relationship in Symfony 2 / Doctrine 2

在 doctine 中更新實體一對多關系的最佳方法是什么? 例如:我有一個名為 booking 的實體,它映射了一對多的 Guest 實體。

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

對我來說,這似乎不對,我想知道其他人如何處理這個問題。

代碼示例:

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

我認為沒有最好的方法,但是您現在的方法不正確。 為什么如果用戶修改了客人,但人數仍然相同(他從列表中刪除了一位客人,但添加了一位新客人)?

無論如何,我認為每次有人編輯時“重置”關系並不是一個糟糕的方法(盡管可能不是最有效的),您只需要從擁有方(客人)設置預訂。 (在多對一關系中,“多”方必須是擁有方)

我會在控制器中這樣做:

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

    }

在來賓實體中,我將添加 function removeUser

 //guest.php
 public function removeBooking(){
       $this->booking=NULL;
 } 

Maybe is more elegant if you create a function in the GuestRepository.php that does what the controller is doing, and in the controller you just call that function.

你真的需要照顧關系的擁有方。 如果您通過擁有方允許版本,即使用預訂更新客人,則默認代碼應用程序/控制台為您提供根本不需要任何類型的自定義:兩個實體都將正確更新。

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

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM