Laravel Eloquant删除子表行-onDelete'cascade'不会删除子表行

问题描述

提前谢谢

我有2张桌子,如下所示

1) users
2) reviews

我创建的架构如下

    Schema::create('users',function (Blueprint $table) {
            $table->id();
            $table->string('first_name',100)->nullable();
            $table->timestamps();
    });
   Schema::create('reviews',function (Blueprint $table) {
            $table->id();
            $table->bigInteger('user_id')->unsigned();
            $table->string('name',100)->nullable();
            $table->timestamps();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });

解决方法

您可以在父模型中尝试以下代码:

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

    static::deleting(function ($model) {
      $model->relations()->delete();
    });
  }

*更新softDeletes

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

  static::deleting(function ($model) {
  if($model->isForceDeleting()){
      $model->relations()->delete();//or forceDelete if child also using softDelete
    });
  }
}