具有热切加载的Laravel缓存模型



我正在尝试在我的项目中缓存某些模型(我使用的是缓存文件驱动程序(。当我加载Model::all((时,laravel调试栏显示4个查询(模型和protected $with属性(。我使用了一种我称之为可缓存的特性。

特点:

namespace AppCacheTraits;
use IlluminateDatabaseEloquentModel;
use Cache;
trait Cacheable {
public static function bootCacheable() {
static::saved(function (Model $model) {
Cache::forever(md5(get_class($model).$model->id)), $model);
});
static::deleted(function (Model $model)
{
Cache::forget(md5(get_class($model).$model->id));
});
static::updated(function (Model $model) {
Cache::forever(md5(get_class($model).$model->id), $model);
});
static::retrieved(function (Model $model) {
Cache::forever(md5(get_class($model).$model->id), $model);
});
}
}

型号:

namespace AppModels;
use IlluminateDatabaseEloquentModel;
use AppClassesChallengeStatus;
use AppCacheTraitsCacheable;
class Challenge extends Model
{
use Cacheable;
protected $with = ['platform', 'brand', 'challengeType'];
public function platform() {
return $this->belongsTo('AppModelsPlatform');
}
public function brand() {
return $this->belongsTo('AppModelsBrand');
}
public function challengeType() {
return $this->belongsTo('AppModelsChallengeType');
}
public function reports() {
return $this->hasMany('AppModelsReport');
}
}

这种方法缺少什么?我想不通。事先谢谢你的帮助。

如果我正确理解您的问题语句,那么您迫切需要加载关系,并执行多个查询来检索数据。这个问题与你的可缓存特性没有任何关系。

Laravel查询生成器总是使用多个查询来加载急切加载的关系。

不幸的是,它并没有合并sql查询来创建更大的sql查询,然后提取记录。

最新更新