我在下面的数据库中有一个用户雇员表
id | name | email | pic
1 Michael michael@mic.com 4
2 John Doe john.doe@gmail.com 4
3 Lorem Ipsum lorem@ipsum.com 4
4 Dolor Amet dolor@amet.com 5
5 Campus Criteria campus@criteria.com
我想在用户ID 5登录时显示数据,他可以查看他的团队,用户ID 5是用户ID 4的图片,用户ID 4是用户ID 1,2和3的图片
这就是我想要的
Dolor Amet
-----------------------------------------------
Michael michael@mic.com
John Doe john.doe@gmail.com
Lorem Ipsum lorem@ipsum.com
我尝试使用紧凑代码,但是它只是显示用户ID 4,而不是用户ID 1,2和3
这是我当前的视图,仅显示用户ID 4,用户ID 1,2和3没有显示
Dolor Amet
-----------------------------------------------
这是我的控制器代码
public function user($id)
{
$pic=Users::where('pic',$id)->get();
foreach($pic as $pics)
{
//dd($pics->id);
$use=Users::where('pic',$pics->id)->get();
}
return view('user',compact(['pic','use']));
}
这是我的刀片服务器代码
<div class="col-md-6">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Your Team</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<table class="table table-bordered">
@foreach($pic as $pics)
<thead class=" text-primary">
<th class="text-center">{{ $pics->name }}</th>
</thead>
@endforeach
<tbody>
@foreach($use as $uses)
<tr>
<td>{{$uses->name}}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
您知道失踪者在哪里吗?
谢谢
答案 0 :(得分:1)
发生这种情况是因为每次执行循环时,旧集合都会被新集合替换
尝试一下
$use = array();
foreach($pic as $pics) {
$use[] = Users::where('pic',$pics->id)->get();
}
答案 1 :(得分:0)
这是控制器的正确代码:-
public function user($id)
{
$pic=Users::where('id',$id)->get();
foreach($pic as $pics)
{
//dd($pics->id);
$use=Users::where('pic',$pics->id)->get();
}
return view('cobauser',compact(['pic','use']));
}
答案 2 :(得分:0)
使用array_push方法组合数组并使其紧凑
public function user($id)
{
$pic=Users::where('id',$id)->get();
$array_combine=array();
foreach($pic as $pics)
{
$use=Users::where('pic',$pics->id)->get();
array_push($array_combine,$use);
}
return view('cobauser',compact(['pic','array_combine']));
}
答案 3 :(得分:0)
在控制器顶部添加use Illuminate\Support\Collection
,
public function user($id)
{
$pic=Users::where('pic',$id)->get();
// use collection
$users = new Collection();
foreach($pic as $pics)
{
//dd($pics->id);
// merge collection with existing content
$users = $users->merge(Users::where('pic',$pics->id)->get());
}
return view('user',compact('pic','users'));
}