'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();
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |