Laravel 5:级联软删除

2022-08-30 13:56:31

我有优惠和服务表。

服务是优惠的子项。到目前为止,我已经建立了软删除报价的功能。如何软删除附加的服务?这是我的代码:

迁移优惠

Schema::create('offers', function(Blueprint $table)
{
    $table->increments('id')->unsigned();
    ...    
    $table->timestamps();
    $table->softDeletes();
});

迁移服务

Schema::create('services', function(Blueprint $table) 
{
    $table->increments('id');
    $table->integer('offer_id')->unsigned();   
    ...
    $table->timestamps();
    $table->softDeletes();
});

Schema::table('services', function($table) 
{
    $table->foreign('offer_id')
          ->references('id')
          ->on('offers');
});

模型报价

use SoftDeletes;
protected $dates = ['deleted_at'];

public function services() {
    return $this->hasMany('App\Service');
} 

模型服务

public function offer() {
    return $this->belongsTo('App\Offer');
} 

删除方法

public function destroy($id)
{
    $offer = Offer::find($id);
    $offer->delete();
}

谢谢你的帮助。


答案 1

我已将此代码放在报价模型中:

protected static function boot() {
    parent::boot();

    static::deleting(function($offer) {
        $offer->services()->delete();
    });
}

并添加了缺失

use SoftDeletes;
protected $dates = ['deleted_at'];

在服务模型中。


答案 2

为此,您应该使用雄辩事件

Offers::deleted(function($offer) {
    $offer->services()->delete();
});

Offers::restored(function($offer) {
    $offer->services()->withTrashed()->restore();
});

推荐