Laravel Eloquent ORM-删除行和所有子关系,并删除事件
我有三个相互关联的模型,一对多: 国家 区域 城市 当我们自动删除国家/地区时,删除所有子项关系,即删除该国家/地区和城市 我正在这样做: 示范国 或 模型区 带有级联删除数据库的选项,请不要提供 更新 我找到了答案 使用查询生成器的闭包删除相关模型 示范国 简单回顾一下:Laravel Eloquent ORM-删除行和所有子关系,并删除事件,laravel,eloquent,laravel-events,Laravel,Eloquent,Laravel Events,我有三个相互关联的模型,一对多: 国家 区域 城市 当我们自动删除国家/地区时,删除所有子项关系,即删除该国家/地区和城市 我正在这样做: 示范国 或 模型区 带有级联删除数据库的选项,请不要提供 更新 我找到了答案 使用查询生成器的闭包删除相关模型 示范国 简单回顾一下: $model->related\u model将返回相关模型。 $model->related_model()将返回关系对象 您可以执行$model->related_model->delete()或$model->rela
$model->related\u model
将返回相关模型。$model->related_model()
将返回关系对象
您可以执行$model->related_model->delete()
或$model->related_model()->get()->delete()
访问模型上的delete()
方法
处理删除相关(或子)模型的另一种方法是在编写迁移时使用外键约束,选中我认为可以在父对象的删除功能中执行此操作:
public function destroy_parent($id)
{
$parent = PARENT::find($id);
foreach ($parent->childs as $child){
$child->delete();
}
$parent->delete();
return redirect(...);
}
您是否尝试过
$this->region()->city()->delete()
?@K.Toress trued,BadMethodCallException:Call to undefined method illumb\Database\Query\Builder::city()在删除模型国家/地区one中的区域之前,您是否尝试过删除该城市?@Björn how make,毕竟在模型国家:$Country->region()->city()->delete()$国家->地区()->删除()
BadMethodCallException:调用集合上的未定义方法Illumb\Database\Query\Builder::city()无法调用delete()啊-在这种情况下,只需循环遍历集合中的所有模型并单独删除它们,或者使用该方法运行。
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;
});
}
public function destroy_parent($id)
{
$parent = PARENT::find($id);
foreach ($parent->childs as $child){
$child->delete();
}
$parent->delete();
return redirect(...);
}