Me: THIS IS A HYBRID QUESTION | Visitor: (wtf?) what this means?
I'm asking 2 questions in one (as it tightly coupled)
Using: Laravel 5.5 & Mysql
1. How do I delete related models in eloquent?
I'm trying to delete User
which has the following relations
belongsTo Address
,
belongsTo Package
,
hasMany Orders
,
hasMany Comments
Orders
cascade when User
or Product
gets deleted
COmments
cascade when User
or Post
gets deleted.
Now how do I can delete User
& automatically have associated orders
& comments
deleted?
when I try to delete with $user->delete()
laravel throws exception:
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`cybertron`.`comments`, CONSTRAINT `comments_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)) (SQL: delete from `users` where `id` = 4)
So I decided to use a transaction to delete, User, associated orders & comments, To make sure everything gets deleted.
But I didn't find any transaction in eloquent but in query builder (DB).
2. if I use transaction from DB & use eloquent to delete user ($user->delete
) will this consider as a transaction?
like:
DB::transaction(function() {
$user->comments->delete();
$user->orders->delete();
$user->delete();
});
If not then how can I have a transaction with Eloquent ?
Any help will be greatly appreciated