Reputation: 25745
I have following entities
- 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();
}
}
- 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
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)
Then in your controller you can just :
$professional->getTimeslots()->clear();
$professional = $em->merge($professional);
$em->flush();
Hope it helps
Upvotes: 8