小编Kam*_*aev的帖子

Laravel Eloquent ORM - 删除行和所有子关系,事件删除

我有三个相互关联的模型:

国家

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)

laravel eloquent laravel-events

7
推荐指数
1
解决办法
1万
查看次数

标签 统计

eloquent ×1

laravel ×1

laravel-events ×1