删除Laravel 6/7中的相关模型 [英] Delete related models in Laravel 6/7
问题描述
有很多相关问题,但不幸的是我找不到有效的解决方案
There are many related questions but unfortunately I can't find working solution
我有Laravel模型,删除此模型后,我想
I have Laravel model and when this model is deleted I want to
- 删除一些相关模型
- 删除模型时运行自定义SQL查询
我的Laravel的模型类看起来很像(如您所见,模型可以具有不同的关系类型)
My Laravel's model class looks like (as you can see models can have different relation types)
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扩展一些课程吗?还是应该将此启动功能放在其他地方?
ModelA is deleted but all related data stays, and I am not sure that it is even being called. Maybe I missed something? Should I extend some class for my ModelA? Or this boot function should be placed somewhere else?
推荐答案
您是否将其级联到ModelB的迁移文件中,如下所示:
Did you cascade it in your migration file of your ModelB like so:
$table->foreignId('modelA_id')
->onDelete('cascade');
->constrained()
`onDelete('cascade')是重要的组成部分,请注意,这是以下方面的简写:
The `onDelete('cascade') is the important part, mind you this is a shorthand for:
$table->unsignedBigInteger('modelA_id');
$table->foreign('modelA_id')->references('id')
->on('modelA')->onDelete('cascade');
这应该为您完成大部分繁重的工作,您可以在 Laravel文档中找到更多信息迁移
This should do most of the heavy lifting for you and you can find more info at Laravel Docs Migrations
如果您不喜欢这种方法,而是希望使用基于事件的方法,那么请尝试在您的ModelA类中这样做:
If you don't like this approach and would prefer an event-based approach then try doing this in your ModelA class:
protected static function booted()
{
static::deleted(function ($modelA) {
$modelA->modelsB()->delete();
// ...
});
}
这篇关于删除Laravel 6/7中的相关模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!