带有Entrust的Laravel 5.4:如何获得具有角色的用户 [英] Laravel 5.4 with Entrust: How to get users with roles

查看:58
本文介绍了带有Entrust的Laravel 5.4:如何获得具有角色的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让所有用户都具有角色,但是角色"字段始终是一个空数组.

I am trying to get all users with roles, but "roles" field is always an empty array.

有4个用户,其中2个已附加至少1个角色,已通过验证.

There are 4 users, 2 of them have at least 1 role attached, verified.

UserController.php

UserController.php

public function getUsers()
{
    $users = User::select('name', 'email', 'type')->with('roles')->get();
    return view('user.list', ['users' => $users, 'lang' => Lang::getLocale()]);
}

即使没有在控制器中使用"with->('roles'),我也会将'roles'字段作为空数组获取.奇怪吗?

I get the 'roles' field as an empty array, even if I don't use "with->('roles')" in the controller. Weird?

如果我在视图中打印每个用户角色,则会得到以下信息:

If i print each user role in the view, I get this:

object(Illuminate\Database\Eloquent\Collection)#281 (1) { ["items":protected]=> array(0) { } }

我做错了什么?

推荐答案

还必须选择与角色相关的主键.口才是首先选择所有用户,然后根据其IDS(主要用户和外部用户)选择关系.如果您不选择主键,他将无法建立关系.

You have to select also primary key, on which roles are related. Eloquent is first selecting all users and then based on their IDS (primary and foreign) is selecting relations. If you dont select primary key, he cant relate relations.

$users = User::select('id', 'name', 'email', 'type')->with('roles')->get();

此外,如果您想指定所需角色中的哪些列,则还必须选择外键.

Also, if you want specifi which columns from roles you want, you have to select foreign key too.

$users = User::select('id', 'name', 'email', 'type')->with(['roles' => function ($query) {$query->select('id', 'name', 'user_id');}])->get();

这篇关于带有Entrust的Laravel 5.4:如何获得具有角色的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆