如何在 laravel 集合中缓存和查找枢轴 table 中的第一个匹配项?

How to cache and find first match in pivot table withing laravel collections?

我有这些 tables

在user_rolestable中有以下字段

如果当前用户,我如何读取所有活动的和未过期的角色并将它们放入缓存中一小时?

有什么方法可以在一个角色停用时清理缓存吗?

关系定义不正确。这应该像下面这样:

用户模型

class User {
    public function roles() {
        return $this->hasMany(App\Role::class);
    }
}

榜样

class Role {
    public function users() {
        return $this->hasMany(App\User::class);
    }
}

现在创建适当的枢轴table来处理这种关系

role_user 架构

Schema::create('role_user', function(Blueprint $table){
    $table->increments('id');

    $table->integer('role_id')->unsigned();
        $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');

    $table->integer('role_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

    $table->timestamp('start_date');
    $table->timestamp('end_date');
    $table->integer('is_active')->default(0); //change to 1 if you want always to be active
});

现在修改我们的 User class 并将 ->withPivot('start_date', 'end_date', 'is_active'); 添加到我们的 roles() 关系中。

更新用户模型

class User {
    public function roles() {
        return $this->hasMany('App\Role::class')->withPivot('start_date', 'end_date', 'is_active');
    }
}

但是等等,这不会让我为我的用户激活角色?!没问题,让我们用查询范围来做到这一点。

class User { 
    //...

    public function scopeOnlyActiveRoles ($query) {
        return $query->whereHas('roles', function($query){
            return $query->where('start_date', '>=', Carbon::now())
                         ->where('end_date', '<=', Carbon::now())
                         ->where('is_active', 1);
        });
    }
}