【问题标题】:Caching scope queries in Laravel在 Laravel 中缓存范围查询
【发布时间】:2016-09-03 11:37:11
【问题描述】:

我正在尝试在我的 Laravel 5.0 项目中实现缓存

我在网上看到的许多缓存示例都不是范围查询,所以我有点困惑。这是来自我的模型的查询/方法,它返回我所有类的 subject_codecourse_no 的串联

/**
 * Get all course codes and titles
 * Used in the autocomplete search
 * @param $query
 * @return mixed
 */
public function scopeAllCourseNo($query) {
    return $query
        ->orderBy('course_no')
        ->groupBy(
            DB::raw("subject_code || ' ' ||  course_no")
        )
        ->get()
        ;
}

由于该方法的第一行只是一个返回,我很好奇我可以将Cache::add('', $allClasses, 30); 查询放在哪里?我应该放在哪里:

if (Cache::has('allClasses'))
{
  return Cache::get('allClasses');
}

非常感谢。

【问题讨论】:

    标签: php laravel caching memcached


    【解决方案1】:

    您不会在模型中缓存。你缓存在你的控制器中。

    所以在你的控制器中:

    您可以使用 Cache add(),但我更喜欢 Cache::remember()。 https://laravel.com/api/5.2/Illuminate/Cache/Repository.html#method_remember

    $classes = Cache::remember('classes', 60, function() {
        return Class::allCourseNo()->get();
    });
    

    【讨论】:

    • 哦,你完全正确。这是完全有道理的。谢谢!
    • 嗨,克里斯。从文档Get an item from the cache, or store the default value 来看,我猜这会将项目保存到缓存中,如果存在,也从缓存中获取?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    相关资源
    最近更新 更多