在角色之后过滤用户

时间:2019-05-29 14:47:26

标签: php laravel laravel-5

我是Laravel的初学者。

我有此代码:

    class User extends Authenticatable implements MustVerifyEmail
    {
        use Notifiable;

        public static $roles = [];


        protected $fillable = ['company_id', 'enable', 'name', 'surname', 'email', 'email_verified_at', 'password', 'counter', 'url_address',  'isCompany', 'isMailing', 'content', 'nip1', 'business1', 'phone1', 'street1', 'number1', 'postal_code1', 'city1', 'country_id1', 'provincial_id1', 'nip2', 'business2', 'phone2', 'street2', 'number2', 'postal_code2', 'city2', 'country_id2', 'provincial_id2', 'nip3', 'business3', 'phone3', 'street3', 'number3', 'postal_code3', 'city3', 'country_id3', 'provincial_id3', 'cash', 'lng', 'lat', 'enable_map', 'remember_token', 'created_at', 'updated_at', 'last_login_at', 'last_login_ip' ];


        protected $hidden = [
            'password', 'remember_token',
        ];


        public function roles()
        {
            return $this->belongsToMany('App\Role');
        }

        public function mainRole()
        {
            return $this->hasOne('App\Role');
        }




        public function hasRole(array $roles)
        {

            foreach($roles as $role)
            {

                if(isset(self::$roles[$role]))
                {
                    if(self::$roles[$role])  return true;

                }
                else
                {
                    self::$roles[$role] = $this->roles()->where('name', $role)->exists();
                    if(self::$roles[$role]) return true;
                }

            }
            return false;
        }

    }
Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->boolean('enable')->default(0);
            $table->string('name', 120)->nullable();
            $table->string('surname', 120)->nullable();
            $table->string('email', 120)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->bigInteger('counter')->default(0);
            $table->string('url_address', 160);
            $table->boolean('isCompany')->default(0);
            $table->boolean('isMailing')->default(0);
            $table->text('content')->nullable();
            $table->string('nip1', 12)->nullable();
            $table->string('business1', 120)->nullable();
            $table->string('phone1', 60)->nullable();
            $table->string('street1', 150)->nullable();
            $table->string('number1', 8)->nullable();
            $table->string('postal_code1', 12)->nullable();
            $table->string('city1', 100)->nullable();
            $table->bigInteger('country_id1')->default(0);
            $table->bigInteger('provincial_id1')->default(0);
            $table->string('nip2', 12)->nullable();
            $table->string('business2', 120)->nullable();
            $table->string('phone2', 60)->nullable();
            $table->string('street2', 150)->nullable();
            $table->string('number2', 8)->nullable();
            $table->string('postal_code2', 12)->nullable();
            $table->string('city2', 100)->nullable();
            $table->bigInteger('country_id2')->default(0);
            $table->bigInteger('provincial_id2')->default(0);
            $table->string('nip3', 12)->nullable();
            $table->string('business3', 120)->nullable();
            $table->string('phone3', 60)->nullable();
            $table->string('street3', 150)->nullable();
            $table->string('number3', 8)->nullable();
            $table->string('postal_code3', 12)->nullable();
            $table->string('city3', 100)->nullable();
            $table->bigInteger('country_id3')->default(0);
            $table->bigInteger('provincial_id3')->default(0);
            $table->decimal('cash', 9, 2)->default(0);
            $table->decimal('lng', 10, 8)->default(0);
            $table->decimal('lat', 10, 8)->default(0);
            $table->boolean('enable_map')->default(0);
            $table->rememberToken();
            $table->timestamps();
            $table->engine = "InnoDB";
        });



Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->engine = "InnoDB";
        });


Schema::create('role_user', function (Blueprint $table) {
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->bigInteger('role_id')->unsigned();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->engine = "InnoDB";
        });

和种子:

public function run()
    {
        DB::table('roles')->insert([
            'name' => 'admin'
        ]);
        DB::table('roles')->insert([
            'name' => 'adminCompany'
        ]);


        DB::table('roles')->insert([
            'name' => 'receptionist'
        ]);

        DB::table('roles')->insert([
            'name' => 'user'
        ]);

    }

我想显示一个具有ADMIN角色的用户的列表。

我有此代码:

public function showAdminList(string $query, string $sortColumn, string $sortMethod) {

    return User::where('email', 'LIKE', '%' . $query . '%')->orWhere('id', 'LIKE', '%' . $query . '%')->orWhere('name', 'LIKE', '%' . $query . '%')->orWhere('surname', 'LIKE', '%' . $query . '%')->orderBy($sortColumn, $sortMethod)->paginate(25);

}

上面的代码向我展示了我在数据库中拥有的所有用户。如何仅显示具有ADMIN角色的用户?

2 个答案:

答案 0 :(得分:1)

检出querying relations in Laravel中的“查询关系存在”。

对于您而言,您的User模型具有多对多roles关系。如果您只想选择具有特定角色的那些用户,则可以这样查询users

$role = 'receptionist';
$receptionists = User::whereHas('roles', function ($query) use ($role) {
    $query->where('name', $role);
})->get();

因此,只需将此whereHas()调用添加到您的查询中,然后从您的请求中读取$role的值即可。

答案 1 :(得分:1)

您可以在User类中使用范围,如下所示:

public function scopeIsAdmin($query)
{
    return $query->whereHas('roles', function ($q) {
        $q->where('name', "ADMIN");
    });
}

然后您可以将其添加到查询中,如下所示:

User :: isAdmin();

您必须确保正确包含OR语句:

   return User::isAdmin()
        ->where(function ($q) use ($query, $sortColumn, $sortMethod) {
            $q->where('email', 'LIKE', '%' . $query . '%')
                ->orWhere('id', 'LIKE', '%' . $query . '%')
                ->orWhere('name', 'LIKE', '%' . $query . '%')
                ->orWhere('surname', 'LIKE', '%' . $query . '%')
                ->orderBy($sortColumn, $sortMethod)->paginate(25);
        })->paginate(25);

我尚未测试上面的代码,因此您可能需要稍作更改。

针对第二个问题,您可以使用其他范围:

public function scopeOfRoleType($query, $types)
{
    return $query->whereHas('roles', function ($q) use ($types) {
        $q->whereIn('name', $types);
    });
}

然后执行User :: ofRoleType(['admin','receptionist])....