Laravel 4.2 观察者中的级联软删除

Laravel 4.2 cascade soft deletes in observers

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

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

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

所以我的 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 删除方法,因此标签没有分离。

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

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