Laravel Eloquent: 如何用名字替换id

Laravel Eloquent: How to replace id with name

我有以下模型和控制器。

User.php

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

RegisterController.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,这个名字在用户中 table 我如何替换报告人 ID 35 以在视图中命名 Yadav

根据我们的讨论

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

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

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

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

@foreach ($report->user as $reportinguser) 
 {{ $reportinguser->name}} 
@endforeach