[英]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
上面的代码retursn
name Reporting Person
========================================================
Ankur /*gets from user table*/ 35 //gets from reporting table
报告人的名称为Yadav,此名称位于用户表中,我如何替换报告人ID 35以在视图中命名Yadav
根据我们的讨论
在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.