6

I have a system where a user is connected to alot of different tables, These tables are also connected to different tables. When I delete a user from my database, every relation associated with that user should also be deleted. My project's relation setup looks like this

- A User user has multiple orders.
- An Order has multiple order items.
- Order Items belong to an order.
- A webshop belongs to a user and a webshop has One Main Setting.
- Main settings belongs to a webshop and has One address.
- Address belongs to main setting

When a user with the id of 1 gets deleted. All orders where the user_id is equal to 1 should also be deleted, No problems there. But the order with the user_id of 1 also has Many order_items. So say for instance this particular order has the id of 3. All order_items with the order_id of 3 should also be deleted. And that is where I ran into this issue.

My attempt

A user gets deleted by doing this

$user = User::find($id);
$user->delete();

A relation gets deleted by doing this:

$user->orders()->delete();

But how do I delete the order items associated with all the orders that get deleted? My attempt was:

$user->orders()->orderitems()->delete();

But unfortunately, that does not work. All the relations in the models are working perfectly fine. So all properties that are useable are

User
- Orders();
- Webshops();
Order
- Orderitems();
Webshop
- Mainsetting();
Mainsetting
- Address();

How can I accomplish the above?

2 Answers2

5

If you are using MySQL (or any RDBMS which supports cascading) you can cascade deleting on database level. If don't, you have to handle it manually on controller or by model event listening functions. See documentation on migrations detailing foreign key constrains.

Schema::create('order_items', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('order_id');
    $table->timestamps();

    $table->foreign('sell_order_id')
          ->references('id')
          ->on('orders')
          ->onDelete('cascade');
});

Note: Laravel supports soft deletes out of the box, as well as cascading soft deletes, see following article https://laravel-news.com/cascading-soft-deletes-eloquent

Kyslik
  • 8,217
  • 5
  • 54
  • 87
train_fox
  • 1,517
  • 1
  • 12
  • 31
0

Use foreign keys and delete cascade in your migrations.

then you only have to delete the orders and automagically the ordesr details will be deleted.

  • 1
    Welcome to SO and thanks for answering! I think your answer would be more helpful to the community if you included an example or explained why your suggestion would work. – DCTID Jan 18 '20 at 21:32