如何将所有能言善辩的孩子一一删除。它的层次结构就像类别 => 课程 => 章节 => 考试

问题描述 投票:0回答:1

当我删除父项时,我有一个问题,我想删除不同模式的所有子项。我希望当我删除类别时,删除类别的所有课程并删除课程的所有章节并删除章节的所有考试

我有 4 个模型 [类别、课程、章节、考试]

类别孩子是课程 当然孩子是章 章节孩子考试了

//Category modal 

public function courses()
{
    return $this->hasMany(Course::class);
}

// Course Model 

public function category()
{
    return $this->belongsTo(Category::class);
}


public function chapters()
{
    return $this->hasMany(CourseChapter::class);
}

// Chapter model

public function course()
{
    return $this->belongsTo(Course::class);
}

public function exams()
{
    return $this->hasMany(Exam::class);
}
laravel eloquent relationship eloquent-relationship
1个回答
1
投票

有两种方法可以做到:

1 - 迁移方式

在每个有外键的迁移中,像这样写:

课程迁移:

$table->foreignId('category_id)->constrained()->cascadeOnDelete();

这将确保一旦删除类别,所有相关课程都会被删除。对其余的人重复相同的过程,例如:

// chapter
$table->foreignId('course_id')->constrained()->cascadeOnDelete();

// exam
$table->foreignId('chapter_id')->constrained()->cascadeOnDelete();

2 - 模型之路

您需要在每个模型中实现 Laravel 的级联删除功能,以下是实现此功能的方法:

// Category model
class Category extends Model
{
    public function courses()
    {
        return $this->hasMany(Course::class);
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($category) {
            $category->courses()->delete();
        });
    }
}

// Course model
class Course extends Model
{
    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function chapters()
    {
        return $this->hasMany(Chapter::class);
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($course) {
            $course->chapters()->delete();
        });
    }
}

// Chapter model
class Chapter extends Model
{
    public function course()
    {
        return $this->belongsTo(Course::class);
    }

    public function exams()
    {
        return $this->hasMany(Exam::class);
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($chapter) {
            $chapter->exams()->delete();
        });
    }
}

// Exam model
class Exam extends Model
{
    public function chapter()
    {
        return $this->belongsTo(Chapter::class);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.