如何在 Laravel 缓存中缓存具有类似角色关系的 auth()->user() 以减少对 DB 的调用?

And*_*vas 4 caching laravel graphql laravel-lighthouse

我正在构建一个使用lighthouse-php的应用程序。因为我不断地为不同的用户设置各种策略,所以我不断地在不同部分应用程序中查询具有角色关系的用户模型,因此,希望将用户存储在Redis数据库中并从那里查询。我阅读了在互联网上找到的几篇文章,例如:laravel-cache-authuser为 Laravel 创建缓存用户提供程序/caching-the-laravel-user-provider-with-a-decorator/,在这里查看了laravel-auth-user的代码,并有点理解这个概念,但很难深入理解 laravel 来找到合适的解决方案......

例如,我正在努力理解如何在 UserObserver 中的事件方法内存储User关系Role,很清楚如何使用一个模型而不是附加的关系来做到这一点。

我有一种感觉,我应该做这样的事情:

class UserObserver
{
    /**
     * @param User $user
     */
    public function saved(User $user)
    {
        $user->load('role');
        Cache::put("user.$user->id", $user, 60);
    }
}
Run Code Online (Sandbox Code Playgroud)

但通过这种方式,我对数据库进行了两次调用,而不是预先加载关系。我如何在事件参数中预加载关系。我尝试添加protected $with = ['role']以便始终加载子模型/关系。但无论如何,我都会对数据库进行更多调用以检索角色或检索用户和角色。

他是我的项目lighthouse-php中的一些简化代码示例。

模式.graphql:

type SomeType {
    someMethod(args: [String!]): [Model!] @method @can(ability: "isAdmin",  model: "App\\Models\\User")
}

type User {
    id: ID
    name: String
    role: Role @belongsTo
}

type Role {
    id: ID!
    name: String!
    label: String!
    users: [User!] @hasMany
}

Run Code Online (Sandbox Code Playgroud)

具有角色关系的用户模型:

type SomeType {
    someMethod(args: [String!]): [Model!] @method @can(ability: "isAdmin",  model: "App\\Models\\User")
}

type User {
    id: ID
    name: String
    role: Role @belongsTo
}

type Role {
    id: ID!
    name: String!
    label: String!
    users: [User!] @hasMany
}

Run Code Online (Sandbox Code Playgroud)

用于某些 graphql 类型字段的用户策略:

class User extends Authenticatabl {
    public function role(): BelongsTo
    {
        return $this->belongsTo(Role::class);
    }
}
Run Code Online (Sandbox Code Playgroud)

Lighouse 自定义查询类,用于通过方法解析字段。

class SomeType {
    public function someMethod(): string
    {
       // this triggers db call rather than receiving `role->name` from redis along with user
       return auth()->user()->role->name;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我进行如下所示的 graphql 查询(请参见下文),它会导致从数据库加载角色关系,而不是缓存。

query {
   user {
     id
     name
     role {
       id
       name
     }
   }
}
Please help.
Run Code Online (Sandbox Code Playgroud)

Eri*_*eer 5

accessor您可以通过为模型role上的属性创建自定义来缓存关系User。一个例子可以是:

<?php 

use Illuminate\Support\Facades\Cache; 

class User extends Authenticatabl {

    public function role(): BelongsTo
    {
        return $this->belongsTo(Role::class);
    }

    public static function getRoleCacheKey(User $user): string
    {
        return sprintf('user-%d-role', $user->id);
    }

    // Define accessor for caching purposes
    public function getRoleAttribute(): Collection
    {
        if ($this->relationLoaded('role')) {
            return $this->getRelationValue('role');
        }
        
        // Replace 3600 for the amount of seconds you would like to cache
        $role = Cache::remember(User::getRoleCacheKey($this), 3600, function () {
            return $this->getRelationValue('role');
        });

        $this->setRelation('role', $role);

        return $role;
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用该rememberForever()函数将其永久缓存。请注意,您必须编写一个实现来手动删除/更新缓存,因为它将永远保留该值。您可以创建一个清除缓存的函数,如下所示:

// In User model
public static function forgetRoleCaching(User $user): bool
{
    return Cache::forget(sprintf(User::getRoleCacheKey($user));
}
Run Code Online (Sandbox Code Playgroud)

您在观察者中的代码可以更新为以下内容:

class UserObserver
{
    /**
     * @param User $user
     */
    public function saved(User $user)
    {
        // in case user role is cached forever
        User::forgetRoleCaching($user);

        $user->load('role'); // will trigger the accessor an should cache again
        Cache::put("user.$user->id", $user, 60);
    }
}
Run Code Online (Sandbox Code Playgroud)