我很难让我的查询缓存。每当我访问我的API时,我都会从DB获得新的结果,而不是我所追求的缓存结果。奇怪的是,如果我查看文件缓存,我可以看到缓存的结果,它们正是我所期望的,但是当我调用API时,我得到了新的结果。下面是相关文件的一些片段。我哪里出问题了?
存储库函数我的API调用:
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;
}模型
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');
});
}
}发布于 2013-12-14 16:07:22
只有在sql查询保持不变的情况下,才能这样缓存。在这种情况下,它不会由于您的top()查询作用域所致。
这是由于查询生成器生成缓存密钥的方式。它将整个查询转换为sql并序列化其绑定,如下所示:
/**
* 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));
}相反,您将不得不手动缓存如下;
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);
}https://stackoverflow.com/questions/20579826
复制相似问题