2013-12-14 77 views
3

我在查詢緩存時遇到問題。每次我打我的API時,我都會從數據庫中獲得新的結果,而不是我要去的緩存結果。奇怪的是,如果我查看文件緩存,我可以看到緩存結果,它們正是我期望的內容,但是當我調用API時,我會得到新的結果。以下是相關文件的一些片段。我在哪裏錯了?Laravel 4查詢緩存

存儲功能我的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'); 
     }); 
} 

} 

回答

11

你只能緩存一樣,如果你的SQL查詢保持完全一致。在這種情況下,它不會由於您的top()查詢範圍。

這是由於查詢構建器生成緩存鍵的方式所致。它整個查詢轉換成SQL和序列化它的綁定,如下面的代碼Laravel obsered:

/** 
* 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); 
} 
+0

謝謝你不只是給出答案,而是解釋爲什麼它是如何。你是一個紳士和學者! –