Eloquent 模型事件仅适用于 Eloquent 模型进程。因此,诸如deleted
,之类的事件deleting
无效,因为您不是从Illuminate\Database\Eloquent\Builder
范围调用Illuminate\Database\Eloquent\Model
。因此,如果要触发模型事件,则需要手动执行。要么改变你的删除方式,要么在运行时delete
覆盖Illuminate\Database\Eloquent\Builder
. 下面是我的示例:
User::whereIn('id', [1, 2, 3, 5])->get(function($model){ $model->delete(); });
或在运行时可自定义
$query = User::whereIn('id', [1, 2, 3, 5]);
$query->onDelete(function($builder)
{
// Manually fire deleted event which I want since I am deleting the model
$builder->get()->each(function($model){
$dispatcher = $model->getEventDispatcher();
$event = "eloquent.deleted: ".get_class($model);
$dispatcher->fire($event, $model);
});
// Now proceed with the normal deletion
// TAKE NOTE: This time you are using
// Illuminate\Database\Query\Builder not Illuminate\Database\Query\Builder so delete function here will act different.
// Assuming User model is on soft delete so i just want to make a soft deletion
$builder->getQuery()->update(['deleted_at'=>\Carbon\Carbon::now()]);
});
因此,通过该示例,正在触发 Eloquent 模型事件。