How to use model events with query builder in laravel

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?


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 .

链接地址: http://www.djcxy.com/p/83196.html

上一篇: Laravel 4.2自定义观察者事件

下一篇: 如何在laravel中使用查询生成器使用模型事件