我有以下模型和控制器。
user.php
public function reporting()
{
return $this->hasMany('AppReporting','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
上述代码retursn
name Reporting Person
========================================================
Ankur /*gets from user table*/ 35 //gets from reporting table
报告人员的名称是Yadav,此名称在用户表中我如何替换报告人员ID 35为yadav in view
根据我们的讨论
在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