Laravel 每个都需要来自两个不同集合的数据

Laravel need data from two different collections in for each

我有一个 for each 循环来遍历记录集合。它具有 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

如何在循环中显示我的用户变量。或者有更好的方法吗?

在我看来,预加载是满足您要求的完美用例。

例如

 $thoughts = Thought::with('user')->get();

    foreach ($thoughts as $thought) {
        echo $thought->user->name;
    }

有关详细信息,请参阅:https://laravel.com/docs/5.6/eloquent-relationships#eager-loading