【发布时间】:2020-03-16 06:15:04
【问题描述】:
我有帖子、评论和通知表
每个帖子都有很多 cmets
每条评论都有很多通知
每个帖子都有很多通知
class Post extends Model
{
public function notifications() {
return $this->morphOne(Notification::class, 'to');
}
public function comments() {
return $this->hasMany(Comment::class, 'post_id');
}
public static function boot() {
parent::boot();
static::deleting(function($post) {
$post->comments()->delete();
$post->notifications()->delete();
});
}
}
class Comment extends Model
{
public function notifications() {
return $this->morphOne(Notification::class, 'to');
}
public static function boot() {
parent::boot();
static::deleting(function($comment) {
$comment->notifications()->delete();
});
}
}
当我删除帖子时,我应该删除通知和 cmets, 但问题是当我删除 cmets 时,通知不会随之删除, 当我直接删除评论时它们被删除,但我删除帖子时需要删除cmets的通知!
【问题讨论】:
-
你能显示你如何删除帖子的代码吗?
-
Laravel 不会实例化它删除的相关模型,这就是为什么直接删除评论会删除通知,而删除帖子删除 cmets 时不会。您必须在删除帖子时实例化 cmets 才能使其正常工作
标签: php laravel eloquent eloquent-relationship