Kam*_*aev 7 laravel eloquent laravel-events
我有三个相互关联的模型:
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
// need an alternative variation of this code
$country->region()->city()->delete();//not working
$country->region()->delete();
return true;
});
}
}
Run Code Online (Sandbox Code Playgroud)
public static function boot() {
parent::boot();
// this event do not working, when delete a parent(country)
static::deleting(function($region) {
dd($region);
//remove related rows city
$region->city()->delete();
return true;
});
}
}
Run Code Online (Sandbox Code Playgroud)
带有级联删除数据库的选项,请不要提供
我找到了答案
对查询构建器使用闭包,删除相关模型
public static function boot() {
parent::boot();
static::deleting(function($country) {
//remove related rows region and city
$country->region->each(function($region) {
$region->city()->delete();
});
$country->region()->delete();//
return true;
});
}
Run Code Online (Sandbox Code Playgroud)
快速回顾一下:
$model->related_model将返回相关模型。
$model->related_model()将返回关系对象。
您可以执行$model->related_model->delete()或$model->related_model()->get()->delete()来访问delete()模型上的方法。
处理删除相关(或子)模型的另一种方法是在编写迁移时使用外键约束,请检查https://laravel.com/docs/master/migrations#foreign-key-constraints
| 归档时间: |
|
| 查看次数: |
11402 次 |
| 最近记录: |