Skip to content
Advertisement

Laravel 8 eloquent query delete

How to delete the aircon in database when there is no any data.

Order and Aircon are many to many relationship.

$orders = Order::with('aircons', 'user')
                ->where('user_id', auth()->id())
                ->orWhere(//if order->aircons count == 0)->delete()
                ->get();

Advertisement

Answer

try whereDoesntHave

$orders = Order::with('user')
                ->whereDoesntHave('aircons')
                ->where('user_id', auth()->id())
                ->get();

Edit:

You can also add new column aircons_count will old number of aircons for every order which will be faster than the above query and run the query like the following:

$orders = Order::with('user')
                ->where('aircons_count', '>', 0)
                ->where('user_id', auth()->id())
                ->get();

Note: make sure to add logic every time you add/remove aircon to an order

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement