我有三个相互关联的模型:
class Country extends Model
{
protected $fillable=['name','sort'];
public $timestamps=false;
public function region(){
return $this->hasMany('App\Models\Region');
}
}
Run Code Online (Sandbox Code Playgroud)
class Region extends Model
{
protected $fillable=['country_id','name','sort'];
public $timestamps=false;
public function country()
{
return $this->belongsTo('App\Models\Country');
}
public function city()
{
return $this->hasMany('App\Models\City');
}
}
Run Code Online (Sandbox Code Playgroud)
class City extends Model
{
protected $table='cities';
protected $fillable=['region_id','name','sort'];
public $timestamps=false;
public function region()
{
return $this->belongsTo('App\Models\Region');
}
}
Run Code Online (Sandbox Code Playgroud)
当我们自动移除国家时,移除所有子项的关系,即移除和这个国家的地区和城市
我这样做:
public static function boot() {
parent::boot();
static::deleting(function($country) {
//remove related rows region and city …Run Code Online (Sandbox Code Playgroud)