Reputation: 8047
In my Gecko.php
i have the following part:
/**
* @ORM\OneToMany(targetEntity="Weight", mappedBy="geckoId")
*/
private $weights;
And in my Weight.php
i have this:
/**
* @ORM\ManyToOne(targetEntity="Gecko", inversedBy="weights")
* @ORM\JoinColumn(name="gecko_id", referencedColumnName="id")
*/
private $geckoId;
My gecko delete action is as follows:
/**
* Deletes a Gecko entity.
*
* @Route("/{name}", name="gecko_delete")
* @Method("DELETE")
*/
public function deleteAction(Request $request, $name)
{
$form = $this->createDeleteForm($name);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('BreedrGeckoBundle:Gecko')->findOneByName($name);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Gecko entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('gecko'));
}
When i click the delete button in my form, i get this error:
An exception occurred while executing 'DELETE FROM Gecko WHERE id = ?' with params [5]:
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (
breedr
.weight
, CONSTRAINTFK_615077FC45D556
FOREIGN KEY (gecko_id
) REFERENCESGecko
(id
))
I don't know how to fix this issue. When there are no weights in the database for a specific gecko, they delete fine, but if there are any weights, it won't delete. Ideally i would like to be able to delete all weight data at the same time that a gecko is deleted
Thanks in advance
Andy
Upvotes: 1
Views: 1038
Reputation: 817
/**
* @ORM\OneToMany(targetEntity="Weight", mappedBy="geckoId", cascade={"persist", "remove"})
*/
private $weights;
Add cascade operations to weights, so whenever Gecko will be updated or deleted, the weights related to it will also be updated / removed.
Upvotes: 1
Reputation: 627
If you don't manually remove the owned entities of a parent entity before deleting it, you'll get errors like this. You can either loop through all the owned entities and delete them manually before deleting the parent, or you can set Doctrine to automatically cascade delete operations:
Upvotes: 1