控制器:
<?php
namespace App\Http\Controllers;
use App\Base\BaseController;
use App\Service\TestService;
use Symfony\Component\HttpFoundation\Request;
class TestController extends BaseController{
public function delete(Request $request)
{
$id = $request->input('id');
$this->service('test')->delete($id);
}
}
service:
<?php
namespace App\Service;
use App\Base\BaseService;
class TestService extends BaseService
{
public function delete($id)
{
//必须查询后再删除,为了使用deleting监听事件,否则无法调用
return Test::where(['id' => $id])->first()->delete();
}
}
Model:
<?php
namespace App\Models;
use App\Base\BaseModel;
class Test extends BaseModel
{
protected $table = "test";
protected $guarded = [];
public function test1()
{
return $this->belongsTo(test1::class, 'test1_id', 'id');
}
/**
*监听事件
*/
protected static function boot()
{
parent::boot();
//删除前执行-调用方式(需删除对象->delete)
static::deleting(function($model){
$model->test1()->delete();
});
//creating - 对象已经 ready 但未写入数据库
//created - 对象已经写入数据库
//updating - 对象已经修改但未写入数据库
//updated - 修改已经写入数据库
//saving - 对象创建或者已更新但未写入数据库
//saved - 对象创建或者更新已经写入数据库
//deleting - 删除前
//deleted - 删除后
//restoring - 恢复软删除前
//restored - 恢复软删除后
}
}