How to use model events with query builder in laravel

限于喜欢 提交于 2020-01-05 07:33:27

问题


I'm using model events such as static::saving, static::saved, etc in my models' static function boot method, and that works great when users save new posts, but when I do something like this:

$post::where('id', $post_id)->update(array('published'=>1));

Updating in this way does not run those model events. My current solution is to just not use this method of updating and instead do:

$post = Post::find($post_id);
$post->published = 1;
$post->save();

But is there any way to make the model events work with the first example using query builder?


回答1:


Model events will not work with a query builder at all.

One option is to use Event listener for illuminate.query from /Illuminate/Database/Connection.php. But this will work only for saved, updated and deleted. And requires a bit of work, involving processing the queries and looking for SQL clauses, not to mention the DB portability issues this way.

Second option, which you do not want, is Eloquent. You should still consider it, because you already have the events defined. This way you can use also events ending with -ing.



来源:https://stackoverflow.com/questions/25181119/how-to-use-model-events-with-query-builder-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!