如何在删除 Laravel 一对多关联模型时触发子模型事件?
一对多关系,Post 拥有多个 Comment。
Comment 模型拥有监控类 CommentObserver:
// CommentObserver.php
public function deleted(Comment $comment)
{
// 重新计算评论作者的 『发布评论数』
$comment->user->recalculateCommentCount();
}
是否可以直接使用以下方法,来触发 CommentObserver 里的事件监控?
// PostObserver.php
public function deleted(Post $post)
{
$post->comments()->delete();
}
高认可度评论:
这个属于批量删除,不会触发观察者滴
需要在服务提供者 boot()方法里注册事件。
这个属于批量删除,不会触发观察者滴
注意:通过 Eloquent 进行批量更新时,被更新模型的 saved 和 updated, deleting 和 deleted 事件不会被触发。这是因为批量更新时,并没有真的获取模型。
楼上说 批量操作的, 这里对于 $post 并不是批量删除, 模型事件是 Post 的 deleted 事件, 跟批量没有关系.