带有预先加载的Laravel缓存模型

时间:2018-12-11 09:26:59

标签: laravel caching model

我正在尝试在项目中缓存某些模型(我正在使用缓存文件驱动程序)。当我加载Model :: all()时,laravel调试栏显示4个查询(模型和protected $with属性)。我正在使用一个称为Cacheable的特征来进行此操作。

特质:

namespace App\Cache\Traits;

use Illuminate\Database\Eloquent\Model;
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 App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Classes\ChallengeStatus;
use App\Cache\Traits\Cacheable;

class Challenge extends Model
{
    use Cacheable;

    protected $with = ['platform', 'brand', 'challengeType'];

    public function platform() {
        return $this->belongsTo('App\Models\Platform');
    }

    public function brand() {
        return $this->belongsTo('App\Models\Brand');
    }

    public function challengeType() {
        return $this->belongsTo('App\Models\ChallengeType');
    }

    public function reports() {
        return $this->hasMany('App\Models\Report');
    }
}

这种方法我缺少什么?我不知道预先感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题说明,则表示您渴望加载关系,并且将执行多个查询以检索数据。 此问题与您的“可缓存”特征无关。

Laravel查询构建器始终使用多个查询来加载渴望的已加载关系。

不幸的是,它不会合并SQL查询以创建更大的SQL查询,然后提取记录。