有很多相关问题,但不幸的是我找不到有效的解决方案
我有 Laravel 模型,当删除该模型时我想要
- 删除一些相关模型
- 删除模型时运行自定义 SQL 查询
我的 Laravel 模型类看起来像(如您所见,模型可以有不同的关系类型)
class ModelA extends Model
{
public functions modelsB() {
return $this->hasMany(ModelB:class);
}
public functions modelsC() {
return $this->belongsToMany(ModelC:class);
}
// other related models
// place where I am expecting actual deleting is happening
public static function boot() {
parent::boot();
self::deleting(function($modelA) {
$modelA->modelsB()->get()->each->delete();
foreach($modelA->modelsC as $modelC){
$modelC->delete();
}
});
}
}
ModelA 被删除,但所有相关数据仍保留,我什至不确定它是否被调用。也许我错过了什么?我应该为我的 ModelA 扩展一些课程吗?或者这个启动函数应该放在其他地方?
关于什么https://laravel.com/docs/7.x/eloquent#events-using-closures https://laravel.com/docs/7.x/eloquent#events-using-closures?就像是
class ModelA extends Model
{
public functions modelsB()
{
return $this->hasMany(ModelB::class);
}
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::deleted(function ($modelA) {
$modelA->modelsB()->delete();
// ...
});
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)