2017-09-04 2 views
1

나는 먼 관계를 잡으려고 노력하고 그것은 작동하지 않습니다. hasManyThrough 일을 시도했지만 belongsToMany 관계에서 작동하지 않는 것으로 보입니다. 쿼리 오류가 발생했습니다. 여기 멀리 떨어진 belongsToMany 통해 belongsToMany

Schema::create('users', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('name'); 
     $table->string('email')->unique(); 
     $table->string('password'); 
     $table->rememberToken(); 
     $table->timestamps(); 
    }); 

    Schema::create('roles', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('name'); 
     $table->timestamps(); 
    }); 


    Schema::create('role_user', function (Blueprint $table) { 
     $table->integer('role_id'); 
     $table->integer('user_id'); 
    }); 

    Schema::create('permissions', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('group'); 
     $table->string('name'); 
     $table->timestamps(); 
    }); 

    Schema::create('permission_role', function (Blueprint $table) { 
     $table->integer('permission_id'); 
     $table->integer('role_id'); 
    }); 

내 모델입니다 : 내가 할 노력하고있어

class User extends AuthUser 
{ 
    // 

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

class Role extends Model 
{ 
    // 

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

이 나에게 Property [permissions] does not exist on this collection instance. 오류를 제공

$user = App\User::find(1); 
Log::info($user->roles->permissions); 

여기

내 마이그레이션합니다.

역할을 통해 사용자 권한을 얻으려면 어떻게해야합니까?

편집 :

if (auth()->check()) { 
    if (auth()->user()->roles->contains('name', 'Admin')) { 
     Gate::before(function() { 
      return true; 
     }); 
    } 
    else { 
     $permissions = []; 

     foreach (auth()->user()->roles as $role) { 
      $permissions = array_merge($permissions, $role->permissions->pluck('name')->all()); 
     } 

     foreach (array_unique($permissions) as $permission) { 
      Gate::define($permission, function() { 
       return true; 
      }); 
     } 
    } 
} 

가 어떻게이 문제를 개선 할 수 있습니다

내가 할 노력하고있어이 추한 솔루션을 함께 왔어요?

+0

사용자 및 역할은 다 대다 관계가 있습니까? –

+0

당신의 관계는 어떻습니까? 한 사용자가 많은 역할을 갖고 그 역할에 많은 권한이 있습니까? –

+0

@ ImmortalDude 예. – kjdion84

답변

0

변경 $ user = App \ USER-> find (1);

to this $ user = App \ User :: find (1); '- (ID')

+0

내 질문에 오타가있었습니다. 그것은 이미'App \ User :: find (1)'입니다. 작동하지 않습니다. – kjdion84

0

마이그레이션 $ 테이블 -> 외국 (> 참조 ROLE_ID) '-에 외래 키를 설정하지 않은이 작동합니다 시도 (역할')에> '; 같은

사용자

+1

외래 키를 사용해도 문제가 해결되지 않습니다. 관계는 외래 키가 설정되지 않고 작동합니다. 나는 또한 외래 키를 추가하고 그것을 시도하고 그 결과는 동일했다. – kjdion84

+0

변경 후 php artisan migrate – Abhishek

1

에 대해 정의 당신이해야 열망로드 같은 그 관계 :

$user = User::with(['roles', 'roles.permissions'])->where('id', 1)->first(); 

이 당신에게 역할의 배열, 그리고 각각의 권한이있는 각 역할을 제공 할 것입니다.

Permission::whereHas('role', function($query) use ($user_id) { 
    return $query->whereHas('user_id', $user_id); 
}); 

위의 쿼리의 아이디어는 먼 관계, you work backwards의 많은 많은을 할 때이다. 때문에

+0

OP를 볼 수 있습니까? 내가하려는 일의 편집에 몇 가지 예제 코드를 보여주었습니다. 나는 기본적으로 코드를 리펙토링하려고 노력하고 있으므로 코드가 적다. 어떤 팁? – kjdion84

+0

추론을 할 수 있습니까? 당신의 예제가 아마도 효과가 있지만 OP가 그의 추론이 실패하는 이유를 이해하게하고, many-to-many 대 many-to-many 관계에서 집계가 작동하지 않는 이유는 : P – Merv

0

그것은 당신에게 Property [permissions] does not exist on this collection instance. 오류를 주었다 모델 역할에서 permissions는 하나의 모델에있는 동안 $user->roles 역할의 컬렉션을 반환 당신이 사용하기 전에

은 기본적으로 당신이 foreach($user->roles as $role)에 있습니다 .. $role->permissions

하지만, 다음은 역할에 따라 권한을 얻을 수 foreach는 필요가 없습니다 샘플 ..입니다

auth()->user()->roles->where('name','=','Administrator')->permissions;

그리고 그것은 관리자의 권한/배열 모음을 반환 할 것입니다 ..

관련 문제