目前没有简单的方法。但是我找到了这个解决方法,到目前为止它对我有用。
首先你必须扩展Illuminate\Database\Query\Builder。
<?php
class ModifiedBuilder extends Illuminate\Database\Query\Builder {
protected $forgetRequested = false;
public function forget()
{
$this->forgetRequested = true;
}
public function getCached($columns = array('*'))
{
if (is_null($this->columns)) $this->columns = $columns;
list($key, $minutes) = $this->getCacheInfo();
// If the query is requested ot be cached, we will cache it using a unique key
// for this database connection and query statement, including the bindings
// that are used on this query, providing great convenience when caching.
$cache = $this->connection->getCacheManager();
$callback = $this->getCacheCallback($columns);
if($this->forgetRequested) {
$cache->forget($key);
$this->forgetRequested = false;
}
return $cache->remember($key, $minutes, $callback);
}
}
然后你必须创建一个扩展 Eloquent 模型的新类。
<?php
class BaseModel extends Eloquent {
protected function newBaseQueryBuilder() {
$conn = $this->getConnection();
$grammar = $conn->getQueryGrammar();
return new ModifiedBuilder($conn, $grammar, $conn->getPostProcessor());
}
}
现在在创建 Eloquent 模型时,而不是扩展 Eloquent 模型扩展新创建的 BaseModel。
现在你可以像往常一样remember查询结果了。
YourModel::remember(10)->get();
当你想丢弃缓存的结果时,你要做的就是
YourModel::forget()->get();
如果你之前记住了结果,那么在清除缓存的结果后,模型会在这段时间内继续记住结果。
希望这会有所帮助。