我有优惠和服务表.
服务是优惠的子女.到目前为止,我已经建立了软删除优惠的功能.我如何软删除附加服务?这是我的代码:
迁移优惠
Schema::create('offers', function(Blueprint $table)
{
$table->increments('id')->unsigned();
...
$table->timestamps();
$table->softDeletes();
});
Run Code Online (Sandbox Code Playgroud)
移民服务
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');
});
Run Code Online (Sandbox Code Playgroud)
型号优惠
use SoftDeletes;
protected $dates = ['deleted_at'];
public function services() {
return $this->hasMany('App\Service');
}
Run Code Online (Sandbox Code Playgroud)
模特服务
public function offer() {
return $this->belongsTo('App\Offer');
}
Run Code Online (Sandbox Code Playgroud)
删除方法
public function destroy($id)
{
$offer = Offer::find($id);
$offer->delete();
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助.
be-*_*ied 36
我已将此代码放在Offer模型中:
protected static function boot() {
parent::boot();
static::deleting(function($offer) {
$offer->services()->delete();
});
}
Run Code Online (Sandbox Code Playgroud)
并添加了缺失
use SoftDeletes;
protected $dates = ['deleted_at'];
Run Code Online (Sandbox Code Playgroud)
在服务模型中.
你应该使用Eloquent事件.
Offers::deleted(function($offer) {
$offer->services()->delete();
});
Offers::restored(function($offer) {
$offer->services()->withTrashed()->restore();
});
Run Code Online (Sandbox Code Playgroud)
如果你想在 Eloquent 模型中获得级联 softDeletes,我强烈建议使用这个库iatstuti/laravel-cascade-soft-deletes
// get it with composer.
$ composer require iatstuti/laravel-cascade-soft-deletes="1.0.*"
Run Code Online (Sandbox Code Playgroud)
入门示例中提供的一个。
<?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);
}
}
Run Code Online (Sandbox Code Playgroud)