How to use model events with query builder in lara

2019-08-10 04:00发布

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条回答
小情绪 Triste *
2楼-- · 2019-08-10 04:35

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.

查看更多
登录 后发表回答