如何在laravel集合中缓存和查找数据透视表中的第一个匹配


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

我有这些表

    用户
  • user_roles

在user_roles表中有以下字段

  • start_date
  • end_date
  • is_active

我怎么能读取所有的活动和未过期的角色,如果当前用户,并把它们在缓存一个小时?

是否有办法在一个角色停用时清理缓存?

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

用户模型
class User {
    public function roles() {
        return $this->hasMany(App'Role::class);
    }
}

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

现在创建适当的数据透视表来处理这个关系

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类,并将->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);
        });
    }
}