doctrine2 - 删除所有onetomany关系

时间:2017-05-15 12:24:43

标签: doctrine-orm one-to-many

我有以下实体

  
      
  1. 专业
  2.   
class Professional extends User
{
    /**
     * @ORM\OneToMany(targetEntity="UserBundle\Entity\Timeslot", mappedBy="professional", cascade={"persist"})
     */
    protected $timeslots;

    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();
        $this->timeslots = new ArrayCollection();
    }

    /**
     * Add timeslot
     *
     * @param \UserBundle\Entity\Timeslot $timeslot
     *
     * @return Professional
     */
    public function addTimeslot(\UserBundle\Entity\Timeslot $timeslot)
    {
        $this->timeslots[] = $timeslot;

        return $this;
    }

    /**
     * Remove timeslot
     *
     * @param \UserBundle\Entity\Timeslot $timeslot
     */
    public function removeTimeslot(\UserBundle\Entity\Timeslot $timeslot)
    {
        $this->timeslots->removeElement($timeslot);
    }

    /**
     * Get timeslots
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getTimeslots()
    {
        return $this->timeslots;
    }

    public function clearTimeslots()
    {
        $this->timeslots->clear();
    }
}
  
      
  1. Timeslot Entity
  2.   
class Timeslot
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(name="day", type="string", length=20, nullable=false)
     */
    private $day;

    /**
     * @ORM\Column(name="starttime", type="time", nullable=true)
     */
    private $startTime;

    /**
     * @ORM\Column(name="endtime", type="time", nullable=true)
     */
    private $endTime;

    /**
     * @ORM\Column(name="available", type="boolean", nullable=false)
     */
    private $available = true;

    /**
     * @ORM\ManyToOne(targetEntity="UserBundle\Entity\Professional", inversedBy="timeslots", cascade={"persist"})
     * @ORM\JoinColumn(name="professional_id", referencedColumnName="id", unique=false, nullable=false)
     */
    private $professional;
}

我想删除给定专业人员的所有时间段,我尝试了

$professional->getTimeslots()->clear();
$em->persist($professional);
$em->flush();

这不会删除数据,如何删除给定专业人员的所有时间段?

1 个答案:

答案 0 :(得分:2)

您可以使用->clear()来实现此目的,但您必须向Professional实体添加一些代码。

@ORM\OneToMany(targetEntity="UserBundle\Entity\Timeslot", mappedBy="professional", cascade={"merge", "persist"}, orphanRemoval=true)
  1. 添加cascade =“merge”
  2. 设置orphanRemoval = true
  3. 然后在你的控制器中你可以:

    $professional->getTimeslots()->clear();
    $professional = $em->merge($professional);
    $em->flush();
    

    希望有所帮助