[英]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.