【问题标题】:Laravel need data from two different collections in for eachLaravel 需要来自两个不同集合的数据
【发布时间】:2018-08-01 20:13:58
【问题描述】:

我有一个 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

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

【问题讨论】:

    标签: laravel eloquent laravel-5.5


    【解决方案1】:

    在我看来,Eager Loading 是满足您要求的完美用例。

    例如

     $thoughts = Thought::with('user')->get();
    
        foreach ($thoughts as $thought) {
            echo $thought->user->name;
        }
    

    更多详情见:https://laravel.com/docs/5.6/eloquent-relationships#eager-loading

    【讨论】:

      猜你喜欢
      • 2014-02-06
      • 1970-01-01
      • 1970-01-01
      • 2015-01-27
      • 1970-01-01
      • 1970-01-01
      • 2013-04-26
      • 2023-03-23
      • 1970-01-01
      相关资源
      最近更新 更多