【问题标题】:Laravel 4.2 cascade soft deletes in observers观察者中的 Laravel 4.2 级联软删除
【发布时间】:2015-04-28 19:42:48
【问题描述】:

我在 Laravel 4.2 中有 3 个相关的表/模型:

  • 用户
  • 帖子
  • 标签

用户的帖子在多态查找表中被标记。

用户和帖子都实现了软删除,我正在使用观察者尝试级联删除用户事件以软删除用户帖子。

所以我的 UserObserver 有:

public function deleted($user){
    // Soft delete their posts 
    \Log::info('Soft-deleting user posts');
    $user->posts()->delete();
}

我的 PostObserver 删除方法有:

public function deleted($post){
    // De-tag the post
    \Log::info('Detaching tags from post');
    $post->tags()->detach();
}

我的问题是,在删除用户成功删除他们的帖子时,没有触发 PostObserver 删除方法,因此标签没有分离。

【问题讨论】:

    标签: laravel laravel-4 observers


    【解决方案1】:

    $user->posts()->delete(); 不会触发任何模型事件。它只会对关系运行DELETE 查询。要使模型事件等 Eloquent 功能正常工作,您必须使用循环将它们一一删除:

    $user->posts->each(function($post){
        $post->delete();
    });
    

    【讨论】:

    • 知道为什么会这样吗?
    • @Tom 是的,因为从不涉及 Post 模型。它只是在数据库上运行一个普通的删除查询。
    猜你喜欢
    • 1970-01-01
    • 2013-06-19
    • 2015-10-06
    • 1970-01-01
    • 2014-12-12
    • 2022-11-02
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多