Reputation: 136
I tried cascade remove on the 'file' entity that keeps my 'expanse' entity from removing. But this doesn't work.
The error:
Cannot delete or update a parent row: a foreign key constraint fails (zioo
.files
, CONSTRAINT FK_6354059F395DB7B
FOREIGN KEY (expense_id
) REFERENCES expenses
(id
))
The file entity code:
/**
* @ORM\ManyToOne(targetEntity="Expense", inversedBy="files", cascade={"remove"})
* @ORM\JoinColumn(name="expense_id", referencedColumnName="id")
*/
private $expense;
The expanse entity code:
/**
* @ORM\OneToOne(targetEntity="File", cascade={"persist"})
* @ORM\JoinColumn(name="file_id", referencedColumnName="id")
*/
private $file = null;
/**
* @ORM\OneToMany(targetEntity="File", mappedBy="expense", cascade={"remove"})
*/
protected $files;
If a expanse gets deleted the file associated with it should be deleted too.
Upvotes: 1
Views: 1642
Reputation: 11242
Using cascade={"remove"} the entity won't be deleted if it is owned by something else. The issue seems to be caused by doctrine, as the expanse entity has 2 relations to file entity and this causes doctrine to "think" that your file entity is owned by something else and not send a delete to database for it, before trying to delete the expanse.
As a result when it tries to delete the expanse this error is thrown.
To test it, remove private $file = null;
relation and will see that it will work.
To overcome this, I suggest to use onDelete="CASCADE"
on the owning side:
/**
* @ORM\ManyToOne(targetEntity="Expense", inversedBy="files", cascade={"remove"})
* @ORM\JoinColumn(name="expense_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $expense;
In this case, you no longer need cascade={"remove"}
:
/**
* @ORM\OneToMany(targetEntity="File", mappedBy="expense")
*/
protected $files;
Doctrine delete relation options
Upvotes: 2