Automatically deleting related rows in Laravel (Eloquent ORM)

后端 未结 13 1718
半阙折子戏
半阙折子戏 2020-11-22 17:03

When I delete a row using this syntax:

$user->delete();

Is there a way to attach a callback of sorts, so that it would e.g. do this auto

13条回答
  •  隐瞒了意图╮
    2020-11-22 17:44

    yeah, but as @supersan stated upper in a comment, if you delete() on a QueryBuilder, the model event will not be fired, because we are not loading the model itself, then calling delete() on that model.

    The events are fired only if we use the delete function on a Model Instance.

    So, this beeing said:

    if user->hasMany(post)
    and if post->hasMany(tags)
    

    in order to delete the post tags when deleting the user, we would have to iterate over $user->posts and calling $post->delete()

    foreach($user->posts as $post) { $post->delete(); } -> this will fire the deleting event on Post

    VS

    $user->posts()->delete() -> this will not fire the deleting event on post because we do not actually load the Post Model (we only run a SQL like: DELETE * from posts where user_id = $user->id and thus, the Post model is not even loaded)

提交回复
热议问题