我将Laravel与UserAuth和Roles一起使用。一切正常。现在,我想添加许多角色。角色应该是递归的。
Schema::create('role_user', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedBigInteger('role_id');
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});
Schema::create('role_role', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->unsignedBigInteger('parent_id');
$table->foreign('parent_id')->references('id')->on('roles')->onDelete('cascade');
$table->unsignedBigInteger('child_id');
$table->foreign('child_id')->references('id')->on('roles')->onDelete('cascade');
});
$user->roles();
给我所有直接分配用户的角色。
示例:
用户在role_user表的Role1中
角色1在role_role表中的角色2中
角色2在role_role表中的角色3中
[$user->roles();
结果是Role1。
$user->roles();
结果应包含Role1,Role2,Role3。不是文字。应该是一个数组
我必须操纵
public function roles()
{
return $this->belongsToMany(Role::class);
}
但是如何?
非常感谢。
您需要建立递归关系:
public function childrenRoles()
{
return $this->hasMany(Role::class, 'parent_id', 'id');
}
public function allChildrenRoles()
{
return $this->childrenRoles()->with('allChildrenRoles');
}
然后您可以使用以下方式访问所有角色
$role = Role::with('allChildrenRoles')->first();
$role->allChildrenRoles->first()->allChildrenRoles; // .. and so on
我已经制定了自己的解决方案,并且效果很好。
Role.php:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
public function belongsToUser(User $user,$int)
{
if ($this->hasUser($user)) {
return true;
}
$children = $this->childrenRoles();
if ($int > 10) {
return false;
}
foreach ($children->get() as $child)
{
if ($child->belongsToUser($user,$int+1)) {
return true;
}
}
return false;
}
public function childrenRoles()
{
return $this->belongsToMany(Role::class, 'role_role', 'child_id', 'parent_id');
}
public function hasUser(User $user)
{
return null !== $this->users()->where('user_id', $user->id)->first();
}
}
User.php
public function roles()
{
$r = Role::where('id','<>', 'null');
foreach ($r->get() as $role)
{
if (! $role->belongsToUser($this,0)) {
$r = $r->where('id', '<>', $role->id);
}
}
return $r->get();
}