首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel 4查询缓存

Laravel 4查询缓存
EN

Stack Overflow用户
提问于 2013-12-14 04:56:57
回答 1查看 3.3K关注 0票数 3

我很难让我的查询缓存。每当我访问我的API时,我都会从DB获得新的结果,而不是我所追求的缓存结果。奇怪的是,如果我查看文件缓存,我可以看到缓存的结果,它们正是我所期望的,但是当我调用API时,我得到了新的结果。下面是相关文件的一些片段。我哪里出问题了?

存储库函数我的API调用:

代码语言:javascript
复制
public function topMonth()
{
    $top = $this->repository->month()->top()->joinUser()->remember(30)->get(['things.id', 'things.votes', 'things.title', 'things.description', 'things.tags', 'things.created_at', 'users.id as user_id','users.username','users.picture as user_picture'])->toArray();

    return $top;
}

模型

代码语言:javascript
复制
class Thing extends Eloquent
{

public function scopeTop($query)
{
    return $query->orderBy('things.votes', 'desc');
}

public function scopeYear($query)
{
    return $query->whereRaw("things.created_at > STR_TO_DATE('" . Carbon::now()->subYear() . "', '%Y-%m-%d %H:%i:%s')");
}

public function scopeMonth($query)
{
    return $query->whereRaw("things.created_at > STR_TO_DATE('" . Carbon::now()->subMonth() . "', '%Y-%m-%d %H:%i:%s')");
}

public function scopeWeek($query)
{
    return $query->whereRaw("things.created_at > STR_TO_DATE('" . Carbon::now()->subWeek() . "', '%Y-%m-%d %H:%i:%s')");
}

public function scopeDay($query)
{
    return $query->whereRaw("things.created_at > STR_TO_DATE('" . Carbon::now()->subDay() . "', '%Y-%m-%d %H:%i:%s')");
}

public function scopeJoinUser($query)
{
    return $query->join('users', function($join)
        {
            $join->on('users.id', '=', 'things.created_by');
        });
}

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-12-14 16:07:22

只有在sql查询保持不变的情况下,才能这样缓存。在这种情况下,它不会由于您的top()查询作用域所致。

这是由于查询生成器生成缓存密钥的方式。它将整个查询转换为sql并序列化其绑定,如下所示:

代码语言:javascript
复制
/**
 * Generate the unique cache key for the query.
 *
 * @return string
 */
public function generateCacheKey()
{
    $name = $this->connection->getName();

    return md5($name.$this->toSql().serialize($this->bindings));
}

相反,您将不得不手动缓存如下;

代码语言:javascript
复制
if (($top = Cache::get('users.top')) === null)
{
    $top = $this->repository->month()->top()->joinUser()->get(['things.id', 'things.votes', 'things.title', 'things.description', 'things.tags', 'things.created_at', 'users.id as user_id','users.username','users.picture as user_picture'])->toArray();
    Cache::put('users.top', $top, 30);
}
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20579826

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档