0

我有以下型号和控制器。

用户.php

public function reporting() 
{
    return $this->hasMany('App\Reporting','user_id','id');
}

注册控制器.php

public function viewUsers()
{

    $users = User::with('reporting')->get();

    return view('users',compact('users'));
 }

users.blade.php

@foreach($users as $user)
        <tr>
            <td>{{$user->name}}</td>
            <td>
                @foreach($user->reporting as $report)
                {{$report->reporting}}
                @endforeach
            </td>
        </tr>
    @endforeach

上面的代码返回

name                                  Reporting Person
========================================================
Ankur /*gets from user table*/          35 //gets from reporting table

报告人的名字是 Yadav,这个名字在用户表中我如何替换报告人 id 35 以在视图中命名 Yadav

4

1 回答 1

2

根据我们的讨论

users表中你有两列id, name,在reportings表中你有user_id, reporting

现在将其添加到您的报告表中

public function user() 
{ 
   return $this->belongsTo(User::class, 'reporting'); 
}

然后在你的父母 foreach 里面的视图中添加这个

@foreach ($report->user as $reportinguser) 
 {{ $reportinguser->name}} 
@endforeach
于 2017-11-27T09:09:16.793 回答