一种缓存 Laravel 中 relation 的方法,欢迎讨论引申思考
目前这个方法只在直接访问属性时生效,使用方法同原 Laravel
的 $model->user
使用的是 laravel
获取属性值时的魔术方法
// 定义 relation
public function user(){
return $this->belongsTo(User::class);
}
// 缓存 relation
public function getUserAttribute() {
$key = '';
$minutes = 0;
return \Cache::remember($key, $minutes, function(){
return $this->user()->getResults() ;
});
}
其他的更高级的缓存方式是可以继承一个 relation builder
的类然后重载 model
里的 relation
方法
例如
// 继承类
class BelongsTo extends \Illuminate\Database\Eloquent\Relations\BelongsTo {
// 重载类中的方法以支持缓存
// 或添加类似 $query->remeber($minutes) 的方法来进行扩展
}
// 在 model 中添加这个方法
public function belongsTo($related, $foreignKey = null, $otherKey = null, $relation = null)
{
// If no relation name was given, we will use this debug backtrace to extract
// the calling method's name and use that as the relationship name as most
// of the time this will be what we desire to use for the relationships.
if (is_null($relation)) {
list($current, $caller) = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
$relation = $caller['function'];
}
// If no foreign key was supplied, we can use a backtrace to guess the proper
// foreign key name by using the name of the relationship function, which
// when combined with an "_id" should conventionally match the columns.
if (is_null($foreignKey)) {
$foreignKey = Str::snake($relation).'_id';
}
$instance = new $related;
// Once we have the foreign key names, we'll just create a new Eloquent query
// for the related models and returns the relationship instance which will
// actually be responsible for retrieving and hydrating every relations.
$query = $instance->newQuery();
// 这里不能直接加 remeber ,因为在 BelongsTo 中会进行 toBase() 操作再生成新的 $query ,添加了是无效的
$otherKey = $otherKey ?: $instance->getKeyName();
// 这里并不是 Laravel 中的 BelongsTo 类
return new \App\BelongsTo($query, $this, $foreignKey, $otherKey, $relation);
}
欢迎大家讨论这种缓存方式的可用性以及易用性,以及更好的缓存 relation
的方法
推荐文章: