I'm trying to understand the cascade
option in Doctrine in Symfony2.
I would like to be able to delete a child entity (and not trigger the foreign key constraint error.)
I have 3 entities:
Report
/**
* @ORM\OneToMany(targetEntity="Response", mappedBy="report")
*/
protected $responses;
/**
* @ORM\OneToMany(targetEntity="Response", mappedBy="report")
*/
protected $sms;
Response
/**
* @ORM\ManyToOne(targetEntity="Report", inversedBy="responses")
*/
protected $report;
SMS
/**
* @ORM\ManyToOne(targetEntity="Report")
*/
protected $report;
Now I would like to delete a Response
entity but I get
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row:
a foreign key constraint fails (mybundle
.sms
, CONSTRAINTFK_B0A93A77BB333E0D
FOREIGN KEY (reportId
) REFERENCESreport
(id
))
Where do I use the cascade
option and which option should I use (detach
or remove
)?
I can do a lot of trial and error to figure this out, but I was hoping for an expert explanation, so I don't overlook something.
Try using
And then update yor schema. It will add database level Cascading
You may also use
cascade=all
for update all actions.Report
Ziumin's answer
method worked when you want to delete a child item (Owning Side).
But if you want to delete a
Response
which is a parent item (Inverse Side), this is whencascade
comes in handy. In theReport
entity I added the following for each of its collections (OneToMany relationships):Report
Now, when I delete a
Report
, it removes all of its associated entries in theResponse
andSMS
tables.