我在缓存查询时遇到问题。每当我点击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');
});
}
}
只有当您的sql查询保持完全相同时,您才能进行这样的缓存。在这种情况下,它不会是由于您的top()
查询范围。
这是由于查询生成器生成缓存键的方式造成的。它将整个查询转换为sql并序列化其绑定,如下面的Laravel代码所示:
/**
* 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);
}