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

How to cache auth()->user() with relationship like role in Laravel cache to reduce calls to DB?

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

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

我觉得我应该这样做:

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

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

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

schema.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
}

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

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

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

class UserPolicy
{
    use HandlesAuthorization;

    public function isAdmin(): Response
    {
        $user = auth()->user();

        return $user->role->name === 'admin'
            ? $this->allow()
            : $this->deny('permission denied');
    }

    public function isManager(): Response
    {
        $user = auth()->user();
        $this->allow();

        return $user->role->name === 'manager' || $user->role->name === 'admin'
            ? $this->allow()
            : $this->deny('Permission Denied');
    }

}

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

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;
    }
}

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

query {
   user {
     id
     name
     role {
       id
       name
     }
   }
}
Please help.

您可以使用 Session 存储您的授权用户和您的关系。

示例:

$auth = Auth::User();
Session::put('user',$auth);

Session::put('relation',$auth->relation);

希望对您有所帮助

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

<?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;
    }
}

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

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

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

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);
    }
}

在“App\Config”路径下创建名为“user.php”的文件。文件应如下所示

<?php

return [
    'role' => ''
];

现在您可以设置配置

config(['user.role' => $example_role]);

然后您可以在需要此数据时从任何文件中读取

config('user.role');

这是我的解决方案,我在中间件中设置了这个配置值,工作完美。