我有一个for循环来遍历记录的集合。它具有user_id,但没有其他用户凭据。我创建了另一个用户集合。如何在我的迭代中包含它?
控制器
public function index(Request $request, $id)
{
$thoughts = Thought::where('id', $id)->orderBy('created_at', 'desc')->paginate(100)->get();
$user = User::where('id', $thoughts->user_id);
return view('backend.pages.thought_list', compact('thoughts, user'));
}
查看
@foreach ($thoughts as $thought)
<tr>
<td class="col-md-1">{{ $user->username}} <span class="user_id_thought">ID - {{ $user->user_id}}</span></td>
<td class="col-md-1">{{ $thought->response }}</td>
<td>{{ $thought->thought_type }}</td>
<td>{{ $thought->id }}</td>
</tr>
@endforeach
如何在循环中显示我的用户变量。还是有更好的方法做到这一点。
答案 0 :(得分:0)
在我看来,快速加载是满足您需求的完美用例。
例如
$thoughts = Thought::with('user')->get();
foreach ($thoughts as $thought) {
echo $thought->user->name;
}
有关更多详细信息,请参见:https://laravel.com/docs/5.6/eloquent-relationships#eager-loading