我有三个模型彼此相关:
class Country extends Model
{
protected $fillable=['name','sort'];
public $timestamps=false;
public function region(){
return $this->hasMany('App\Models\Region');
}
}
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');
}
}
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');
}
}
当我们自动删除国家/地区时,删除所有子项目关系,即删除此区域和城市
我这样做:
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;
});
}
}
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;
});
}
}
带有级联删除数据库的选项,请不要提供
我找到了答案
使用闭包查询构建器,删除相关模型
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;
});
}
Laravel Eloquent ORM - Removing rows and all the inner relationships
答案 0 :(得分:1)
快速回顾一下:
$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
答案 1 :(得分:1)
我认为你可以在父对象的删除函数中做到这一点:
public function destroy_parent($id)
{
$parent = PARENT::find($id);
foreach ($parent->childs as $child){
$child->delete();
}
$parent->delete();
return redirect(...);
}