小编Mah*_*bir的帖子

在 laravel 中删除一行时删除所有关系

我有帖子、评论和通知表

每个帖子都有很多评论

每个评论都有很多通知

每个帖子都有很多通知

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();
        });
    } 
}
Run Code Online (Sandbox Code Playgroud)
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();
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

当我删除帖子时,我应该删除通知和评论,但问题是当我删除评论时,通知不会随之删除,当我直接删除评论但我需要删除评论时,它们会被删除删除帖子时评论的通知!

php laravel eloquent eloquent-relationship

5
推荐指数
1
解决办法
5505
查看次数

标签 统计

eloquent ×1

eloquent-relationship ×1

laravel ×1

php ×1