gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:29:30 24 4
gpt4 key购买 nike

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

国家

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

最佳答案

简单回顾一下:
$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

关于Laravel Eloquent ORM - 删除行和所有子关系,事件删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34989701/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com