簡體   English   中英

Laravel 用戶角色遞歸

[英]Laravel User Roles recursive

我將 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

我制作了自己的解決方案,效果很好。

角色.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();
}



}

用戶.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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM