douwen7331 2013-08-20 11:48
浏览 185
已采纳

“缓存”Eloquent查询的最佳方式

I have an application that runs function like SomeModel::getValue($month, $year, $departmentId) in a loop.

getValue creates a query and returns the result:

return self::where('department_id', '=', $department_id)
           ->where('year', '=', $year)
           ->where('month', '=', $month)
           ->pluck('value');

In this loop it might call the same arguments more than once. I wanted to know the best way to avoid creating a new query each time i want to get the data.

I thought about creating a static array inside the model and match against it every time getValue is being called. If value exists in the array just return it, if not create a query.

Is my solution ok? you have any other ideas? thank you!

I'm using Laravel 4

  • 写回答

1条回答 默认 最新

  • dsk920417 2013-08-20 11:54
    关注

    Static caching is the best method as long as you are ok with the implications:

    • You only cache per request -- if the user refreshes, you recreate the cache from scratch
    • You will have some memory overhead to keep the populated static array. This, on its own, is not a big deal until you have to take into account concurrency (each request has its own static arrays).

    Depending on the maximum size of the static array, it might be best to decide how long your cache is valid for (eg 1 minute), and push the cache to some form of cross-request cache so that you can reuse it ( see APC, Memcached, or even simple MySQL INSERT in a table) -- in all cases just save the serialized array and load it as an additional step before doing the actual computation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?