Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25745

doctrine2 - delete all onetomany relations

I have following entities

  1. Professional
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
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;
}

I want to delete all timeslots for a given professional, I tried doing

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

This does not delete the data, how do I delete all timeslots for a given professional?

Upvotes: 1

Views: 2909

Answers (1)

Erwan Haquet
Erwan Haquet

Reputation: 348

You can achieve this with ->clear(), but you have to add some code to your Professional entity.

@ORM\OneToMany(targetEntity="UserBundle\Entity\Timeslot", mappedBy="professional", cascade={"merge", "persist"}, orphanRemoval=true)
  1. Adding a cascade="merge"
  2. Set orphanRemoval=true

Then in your controller you can just :

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

Hope it helps

Upvotes: 8

Related Questions