简体   繁体   中英

Unable to delete records from the database in a one-to-many relationship

In a Symfony 2.8 project, I have a PersonDetail object that has a one-to-many relationship with CompanyProductionUnits:

use Doctrine\ORM\Mapping as ORM,
    Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * AppBundle\Entity\GeneralData\PersonDetail
 *
 * @ORM\Table(name="person_detail")
 * @ORM\Entity(repositoryClass="PersonDetailRepository")
 * @ORM\HasLifecycleCallbacks
 */
class PersonDetail
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var ArrayCollection $companyProductionUnits
     *
     * @ORM\OneToMany(targetEntity="PersonDetailCompanyProductionUnit", mappedBy = "personDetail", cascade={"persist", "remove"})
     */
    private $companyProductionUnits;
}


<?php
namespace AppBundle\Entity\GeneralData;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * AppBundle\Entity\GeneralData\PersonDetailCompanyProductionUnit
 *
 * @ORM\Table(name="person_detail_company_production_unit")
 * @ORM\Entity()
 * @ORM\HasLifecycleCallbacks
 */
class PersonDetailCompanyProductionUnit {
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var Company $company
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\GeneralData\CompanyProductionUnit")
     * @ORM\JoinColumn(name="company_production_unit_id", referencedColumnName="id")
     */
    protected $companyProductionUnit;

    /**
     * @var PersonDetail $personDetail
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\GeneralData\PersonDetail", inversedBy="companyProductionUnits")
     * @ORM\JoinColumn(name="person_detail_id", referencedColumnName="id")
     */
    protected $personDetail;
}    

I would like to empty the company units array collection when the user does a specific operation in a form, setting the moveEmployee value to 1. For this reason, when the value of moveEmployee is 1, I remove the company production unit objects from the collection. But the record are not deleted from the database. Why?

Here you are the form handler:

<?php
namespace AppBundle\Form\Handler;

use AppBundle\Entity\GeneralData\PersonDetailCompanyProductionUnit;
use Symfony\Component\HttpFoundation\Request,
    Symfony\Component\Form\FormInterface,
    Symfony\Component\HttpFoundation\Session\Session;

use Doctrine\ORM\EntityManager;
use AppBundle\Entity\GeneralData\PersonDetail;

class CompanyProductionUnitEmployeeFormHandler {

    private $entityManager;
    private $session;

    public function __construct(
        EntityManager $entityManager,
        Session $session
    )
    {
        $this->entityManager = $entityManager;
        $this->session = $session;
    }

    public function handle(FormInterface $form, Request $request, $message)
    {
        if(!$request->isMethod('POST')) {
            return false;
        }

        $form->bind($request);

        if(!$form->isValid()) {
            return false;
        }

        $data = $request->request->get('company_production_unit_employee');

        $productionUnit = $this->entityManager
            ->getRepository('AppBundle\Entity\GeneralData\CompanyProductionUnit')
            ->find($data['productionUnit']);

        $personDetail = $this->entityManager
            ->getRepository('AppBundle\Entity\GeneralData\PersonDetail')
            ->find($data['personDetail']);

        if($data['moveEmployee'] == 1) {
            //first try
            foreach($personDetail->getCompanyProductionUnits() as $unit) {
                $this->entityManager->remove($unit);
            }

            //I tried also in the following way but without success
            //$personDetail->companyProductionUnits->clear();

        }

        $personDetailCompanyProductionUnit = new PersonDetailCompanyProductionUnit();
          $personDetailCompanyProductionUnit->setPersonDetail($personDetail);
              $personDetail->addCompanyProductionUnit($personDetailCompanyProductionUnit);

        $this->persist($personDetail, $message);

        return true;
    }

    public function persist(PersonDetail $personDetail, $message)
    {    
        $this->entityManager->persist($personDetail);
        $this->entityManager->flush();

        $this->session->getFlashBag()->add('success', $message);
    }
}

I did a quick look around and think this might be the most helpful, judging from what you asked, I think this document might help you figure it out. Working with associations

I have casually discovered that my code works when I apply both the strategies I tried in my previous example. As a consequence, the solution is using the following code in the form handler:

if($data['moveEmployee'] == 1) {
    foreach($personDetail->getCompanyProductionUnits() as $unit) {
        $this->entityManager->remove($unit);
    }

    $personDetail->companyProductionUnits->clear();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM