我有优惠和服务表。
服务是要约的子女。到目前为止,我已经建立了软删除优惠的功能。我如何软删除附加服务?这是我的代码:
迁移优惠
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();
}
感谢您的帮助。
答案 0 :(得分:34)
我已将此代码放在Offer模型中:
protected static function boot() {
parent::boot();
static::deleting(function($offer) {
$offer->services()->delete();
});
}
并添加了缺失
use SoftDeletes;
protected $dates = ['deleted_at'];
在服务模型中。
答案 1 :(得分:7)
您应该使用Eloquent events。
Offers::deleted(function($offer) {
$offer->services()->delete();
});
Offers::restored(function($offer) {
$offer->services()->withTrashed()->restore();
});
答案 2 :(得分:3)
如果您想在您的Eloquent模型中获得级联softDeletes,我强烈建议您使用此库iatstuti/laravel-cascade-soft-deletes
// get it with composer.
$ composer require iatstuti/laravel-cascade-soft-deletes="1.0.*"
入门示例中提供的那个。
<?php
namespace App;
use App\Comment;
use Iatstuti\Database\Support\CascadeSoftDeletes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes, CascadeSoftDeletes;
protected $cascadeDeletes = ['comments'];
protected $dates = ['deleted_at'];
public function comments()
{
return $this->hasMany(Comment::class);
}
}
答案 3 :(得分:2)
你可以这样做。
self::deleting(function($offer) {
$offer->services()->delete();
});
self::restoring(function ($offer) {
$offer->services()->restore();
});
在删除/恢复父(要约)之前,您应首先删除/恢复子记录(服务)。如果不这样做,将触发参照完整性MySql错误。