我想抓住一個遙遠的關係,它不工作。我試過做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');
}
}
我想要做的事:
$user = App\User::find(1);
Log::info($user->roles->permissions);
這給了我一個Property [permissions] does not exist on this collection instance.
錯誤。
如何通過角色獲取用戶權限?
編輯:
我想出了這個醜陋的解決方案,我想要做的事:
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;
});
}
}
}
我該如何提高呢?
用戶和角色有多對多的關係? –
你的關係是什麼樣的?它是一個用戶有多個角色,這些角色有很多權限? –
@ImmortalDude是的。 – kjdion84