我有一个名为role_users
的表,该表有3列:id
,user_id
和role_id
和所有用户的表Users
。我需要为我站点中的每个用户获取ID角色,因为我想为individuals
使用一个图标(ID 1),为organizations
使用另一个图标(ID 100)。
我的角色表在这里:https://imgur.com/a/DpthH7g。
Controller.php
$myRole = Role::join(
'users',
function($join) {
$join->on('roles.id', '=', 'users.id');
}
)
->groupBy('users.id')
->selectRaw(
implode(',', [
'users.id AS id',
])
)
->get();
return view('noticeboard.noticeboard',$data)
->with(compact('myRole'));
dd($ myRole)
[{"id":1}];
查看
@if($myRole->id == 1)
<a href="{{ url('') }}/{{ $contact->username }}">{{ $contact->username }}</a></h3>
<i class="icon-user"></i>
@else
<i class="icon-trophy"></i>
@endif
答案 0 :(得分:1)
您应该为此尝试雄辩的关系。
在用户模型中,定义与角色的hasOne关系
Z_LVAL_P(op1) == Z_LVAL_P(op2)
然后在Controller中使用“急切加载”
public function role()
{
return $this->hasOne('App\Role','user_id');
}
然后在视图中使用foreach循环获取具有角色的所有用户
$users = User::with('role')->get();
return view('noticeboard.noticeboard',compact('users'));
除非您真的不想使用关系。然后在“用户”表上使用join。