Laravel 4查询缓存

sea*_*ean 3 php caching laravel eloquent

我在查询缓存时遇到问题.无论何时我点击我的API,我都会从数据库中获得新的结果,而不是我想要的缓存结果.奇怪的是,如果我查看文件缓存,我可以看到缓存的结果,它们正是我期待的,但是当我调用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;
}
Run Code Online (Sandbox Code Playgroud)

模型

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');
        });
}

}
Run Code Online (Sandbox Code Playgroud)

Gar*_*een 11

如果您的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));
}
Run Code Online (Sandbox Code Playgroud)

相反,你必须像这样手动缓存这个;

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);
}
Run Code Online (Sandbox Code Playgroud)