有没有更好的方法一次使用委托获取所有用户的角色名称


Is there any better way to get all the users Role name using Entrust at a time

我需要用户角色和权限管理,所以我想尝试一下委托包以节省时间。使用它时,我需要在路由中显示所有用户的用户名和角色名称,所以我在路由中执行此操作

Route::get("user-with-role", function(){
$user = User::with('roles')->get();
foreach (User::with('roles')->get() as $u)
{
echo $u->username;
    foreach ($u->roles as $role) {
        echo " is ".$role->name;
        echo "<br>";
    }
}
});

有没有更好的方法来获取角色名称而不是内部 foreach 循环?

这是我的用户表的数据库结构

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

谢谢。

如果您希望

包含用户和角色的架构结构(如果存在),我能提供更多帮助。 以及您的用户模型和角色模型。 但这是应该发生的事情的要点。 如果你想要一个更好的答案...我需要你更多。 理想情况下,您应该能够在用户和角色之间进行SQL联接,或者如果您在类中定义了关系,则可以访问与Eloquent ORM的关系。

您不应该在路由函数中回显 HTML...这对你没有任何好处。 同样在您的路由函数中,您应该返回一些东西,因为这是一个 GET 请求,服务器将期待响应......

路线

Route::get("users", function() {
    $users = User::select('username', 'role')->with('roles')->get();
    return View::make('SOME VIEW')->withUsers($users);
});

刀片视图

<table>
    <thead>
        <tr>
            <th>Username</th>
            <th>Role</th>
        </tr>
    </thead>
    <tbody>
        @foreach ($users as $user)
            <tr>
                <td>{{ $user->username }}</td>
                <td>{{ $user->role }}</td>
            </tr>
        @endforeach
    </tbody>
</table>

用户与角色的关系

现在生成委托迁移

$ php artisan entrust:migration

它将生成<timestamp>_entrust_setup_tables.php migration。您现在可以使用工匠迁移命令运行它:

$ php artisan migrate

迁移后,将出现两个新表:包含现有角色的角色及其权限和assigned_roles,表示用户和角色之间的多对多关系。

在这里你应该有你的多对多关系,你这样做了吗?