0

I have 3 tables

Client
-----------
|id|client|
-----------
|1 |client|
-----------

Items
---------------------
|id|client_id|item  |
---------------------
|1 |   1     |item 1|
---------------------
|2 |   1     |item 2|
---------------------
Images
----------------------
|id|item_id|  image  |
----------------------
|1 |  1    |image.jpg|
----------------------
|2 |  1    |image.jpg|
----------------------
|3 |  2    |image.jpg|
----------------------
|4 |  2    |image.jpg|
----------------------

As you can see, table client can have many items, and table items can have many images. when a client will be delete, the items and the images of those items should be deleted to.

I tried to do something like this, but with no result.

$client->items()->images()->delete();

I also tried to make the full call but that only delete the client, like

$client->with(array('items' => function($items){
   $items->with('images');
}))->delete()

Its there a way to delete the client, the items of that client and the images of those items in a single transaction?

in adition i have read about Model events but honestly i do not understand it, i read i could use the next code, in what model do i put it? and what should i delete inside the deleting function

protected static function boot() {
    parent::boot();

    static::deleting(function() {
       //what go in here?
    });
}
Carlos Salazar
  • 1,818
  • 5
  • 25
  • 48

1 Answers1

0

You can update your database's foreign key to delete on cascade.

$table->foreign('item_id')->references('id')->on('items')->onDelete('cascade');

That way you only have to delete the parent model.

novoalg
  • 79
  • 2
  • 9