与Laravel 5.6关联破坏缓存

时间:2018-09-03 22:04:56

标签: laravel

我有一个名为Tournament的模型,其中每个Tournament都与它的某些关系一起缓存,使用每个模型的密钥(即tournament.1)。

return \Cache::remember('tournament.' . $id, 60*24*7, function() use ($id) {
    return Tournament::where('id', $id)
        ->with(['prizes', 'sponsor'])
        ->firstOrFail();
});

当我更新关系时,我想忘记那场比赛的钥匙。我知道我可以使用这样的事件:

public static function boot()
{
    static::saving(function ($prize) {
        \Cache::forget('tournament.' . $prize->tournament->id);
    });

    return parent::boot();
}

但是,这样做意味着我还必须针对所有其他关系重复此代码。我可能可以为此创建一个特征,但是是否有更好的方法来完成我想要实现的目标?

1 个答案:

答案 0 :(得分:0)

我最终用特质解决了这个问题。

namespace App\Traits;

trait ShouldCacheBust
{
/**
 * The "booting" method of the model.
 */
public static function boot()
{
    static::saving(function ($model) {
        $cacheKey = static::cacheBustKey($model);

        if ($cacheKey) {
            \Cache::forget($cacheKey);
        }
    });

    return parent::boot();
}

/**
 * Return the key to be removed from Cache
 * 
 * @param Model $model
 * @return string|null
 */
abstract public function cacheBustKey(Model $model);
}

然后像这样使用它:

/**
 * Return the key to be removed from Cache
 *
 * @param Model $model
 * @return mixed|string
 */
public static function cacheBustKey(Model $model)
{
    return 'tournament.' . $model->id;
}
相关问题