您如何忘记Laravel中缓存的Eloquent模型? [英] How would you forget cached Eloquent models in Laravel?

查看:213
本文介绍了您如何忘记Laravel中缓存的Eloquent模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于Laravel的理论问题.

Theoretical question on Laravel here.

所以我要做的缓存示例是:

So Example of the caching I'd do is:

Article::with('comments')->remember(5)->get();

理想情况下,我希望为Article更新提供一个事件,该事件是当该模型的实例ID(已缓存)更新时,我想忘记该键(即使它是整个查询结果被忘记了)而不只是一个模型实例),有可能这样做吗?

Ideally I'd like to have an event for Article updates that when the ID of a instance of that model (that's already cached) is updated I want to forget that key (even if it's the whole result of the query that's forgotten instead of just that one model instance), it is possible to do so?

如果没有某种方法可以合理地实现这一目标?

If not is there some way to implement this reasonably cleanly?

推荐答案

所以我一直在寻找与OP相同的问题的答案,但对解决方案并不满意.因此,我最近开始研究此框架并查看框架的源代码,发现remember()方法接受名为key的第二个参数,由于某种原因,该参数尚未在其

So i was looking for an answer to the same question as OP but was not really satisfied with the solutions. So i started playing around with this recently and going through the source code of the framework, I found out that the remember() method accepts second param called key and for some reason it has not been documented on their site (Or did i miss that?).

现在,关于此的好事是,数据库构建器使用在app/config/cache.php下配置的相同的缓存驱动程序,或者我应该说这里已说明的相同的缓存系统-官方站点,例如Cache::get()Cache::add()Cache::put()等.但是除非您知道,否则我不建议您使用其他方法你在做什么.

Now good thing about this is that, The database builder uses the same cache driver which is configured under app/config/cache.php Or should i say the same cache system that has been documented here - Cache. So if you pass min and key to remember(), you can use the same key to clear the cache using Cache::forget() method and in fact, you can pretty much use all the Cache methods listed on the official site, like Cache::get(), Cache::add(), Cache::put(), etc. But i don't recommend you to use those other methods unless you know what you're doing.

这是您和其他人了解我的意思的一个例子.

Here's an example for you and others to understand what i mean.

Article::with('comments')->remember(5, 'article_comments')->get();

现在,上面的查询结果将被缓存并与article_comments键相关联,该键可随时用于清除它(在我的情况下,我会在更新时执行此操作).

Now the above query result will be cached and will be associated with the article_comments key which can then be used to clear it anytime (In my case, I do it when i update).

所以现在,如果我想清除该缓存,无论它记住多少时间.我可以通过调用Cache::forget('article_comments');来做到这一点,它应该可以按预期工作.

So now if i want to clear that cache regardless of how much time it remembers for. I can just do it by calling Cache::forget('article_comments'); and it should work just as expected.

希望这对所有人都有帮助:)

Hope this helps everyone :)

这篇关于您如何忘记Laravel中缓存的Eloquent模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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