1

覆盖标准方法(例如delete(),并使用钩子方法,例如Post::deleting())非常有用,但似乎Query Builder(或Fluent?)对象不通过这些方法处理它们的方法。

例如,以下进程监听钩子,并且可以被覆盖:

$user = User::find(1);
$user->delete();

以下示例不会:

User::whereId(1)->delete();

我可以尝试确保永远不要使用速记方法,但最好是,有没有办法捕捉delete()第二个示例中的动作?

4

1 回答 1

0

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 模型事件。

于 2015-01-19T07:46:18.990 回答