I have three models that relate to each other one to many:
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');
}
}
When we remove the country automatically, remove all child item relationship, that is, removed and regions and city this country
I am doing so:
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;
});
}
}
options with cascading deletes database, please do not offer
I found the answer
use closure for query builder, to remove related models
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
Just a quick recap:
$model->related_model
will return the related model.
$model->related_model()
will return the relation object.
You can do either $model->related_model->delete()
or $model->related_model()->get()->delete()
to access the delete()
method on the model.
Another way of handling the deletion of related (or sub) models is to use foreign key constraints when you write your migrations, check https://laravel.com/docs/master/migrations#foreign-key-constraints