如何在Laravel中通过查询生成器使用模型事件 [英] How to use model events with query builder in laravel

查看:57
本文介绍了如何在Laravel中通过查询生成器使用模型事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在模型的静态函数启动方法中使用模型事件,例如static :: Saveing,static :: saved等,当用户保存新帖子时,效果很好,但是当我执行以下操作时:

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.

一种选择是对/Illuminate/Database/Connection.php中的illuminate.query使用事件侦听器.但这仅适用于savedupdateddeleted.并且需要一些工作,包括处理查询和查找SQL子句,更不用说这种方式的数据库可移植性问题了.

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.

您不需要的第二个选项是口才".您仍然应该考虑它,因为您已经定义了事件.这样,您还可以使用以-ing结尾的事件.

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.

这篇关于如何在Laravel中通过查询生成器使用模型事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆