I have a table named Child
that has a Foreign key from Parent
table. Now, I need to delete a parent row with its children completely. I use this code in redbeanphp
:
R::trash(parent);
But it throws constraint exception because of reference in child table.
how can I delete a bean with its children in one step?
If you want this behavior to be out-of-the-box, you can define the foreign key to do so. In MySQL, this would be done with ON DELETE CASCADE
when defining the foreign key. Here's the documentation.
If you want it to be done on the PHP side, you'd have to do it manually;
R::exec('DELETE FROM child_table WHERE parent_id = :pid', array('pid' => $parent->id));
(there might be a more "bean" way to do this, I haven't really gotten into it though)