一对多的关系不适用于Laravel

时间:2016-04-06 06:55:40

标签: laravel laravel-5 eloquent laravel-5.1

我有三个相关的模型。首先,我拥有属于角色的用户。另一方面,角色有很多角色。角色属于许多权限,权限属于许多角色。我正在使用jeffrey方式建议的AuthServiceProvider。但是,当我获取用户的所有权限时,我遇到错误,即“在布尔值上调用成员函数getKey()”。有人可以帮我这个。请参阅以下代码。

user.php的

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

public function assignRole($role)
{
    return $this->roles()->save(
        Role::whereName($role)->firstOrFail()
    );
}

public function hasRole($role)
{
    if(is_string($role)){
        return $this->role->contains('name', $role);
    }

    return !! $role->intersect($this->role)->count();

}

Role.php

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

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

    public function givePermissions(Permission $permission)
    {
        return $this->permissions()->save($permission);
    }
}

Permission.php

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

AuthServiceProvider

public function boot(GateContract $gate)
{
    $this->registerPolicies($gate);

    //get all permissions
    foreach ($this->getPermissionTo() as $permission ) {

        $gate->define($permission->name, function($user) use ($permission){
            return $user->hasRole($permission->roles);
        });
    }
}

public function getPermissionTo()
{
    return Permission::with('roles')->get();
}

最后,继承了具有role_id

外键的用户表
Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('role_id')->unsigned();

        $table->string('id_no')->unique()->index();
        $table->string('u_first_name');
        $table->string('u_middle_name');
        $table->string('u_last_name');
        $table->string('email')->unique();
        $table->string('password');

        $table->rememberToken();
        $table->timestamps();
    });

0 个答案:

没有答案