Laravel 5.4 with Entrust: How to get users with roles

柔情痞子 提交于 2020-02-05 02:12:09

问题


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

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

UserController.php

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

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) { } }

What I am doing wrong?


回答1:


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();


来源:https://stackoverflow.com/questions/44179572/laravel-5-4-with-entrust-how-to-get-users-with-roles

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!