[英]How to get user's name from user_id in laravel?
I have 2 table 1st fund
2nd users
I have registered member name in users
table while in fund
table user_id
of registered member. 我在注册会员的fund
表user_id
中有2个表第1 fund
第2 users
我在users
表中注册了会员名。 I want to show users name in a table where I am able to show its user_id
. 我想在一个表中显示用户名,我可以在其中显示其user_id
。
<div class="deposit-body">
<table class="table main-table">
<tbody>
<tr class="head">
<th>Name</th>
<th>Date</th>
<th>Currency</th>
<th>Amount</th>
</tr>
@foreachFund::with('user')->where('created_at', '>', Carbon::now()->subHours(24))->orderBy('id', 'desc')->take(10)->get()
<tr>
<td>{{ $fund->user_id }}</td>
<td>{{ $fund->updated_at}}</td>
<td><strong>{{$basic->currency}}</strong></td>
<td><strong>{{ $fund->total }}</strong></td>
</tr>
@endforeach
</tbody>
</table>
</div>
I have pasted following code to my Fund model. 我已将以下代码粘贴到我的基金模型中。 But it is not working. 但它没有用。
public function user(){
return $this->belongsTo('App\User', 'user_id');
}
Use relationship
to access user object. 使用relationship
访问用户对象。
@foreach(Fund::with('user')->where('created_at', '>', Carbon::now()->subHours(24))->orderBy('id', 'desc')->take(10)->get() as $fund)
<tr>
<td>{{ $fund->user->name }}</td>
</tr>
@endforeach
Looks like not all funds have user_id
filled. 看起来并非所有资金都填写了user_id
。 In this case, you should use the optional()
helper. 在这种情况下,您应该使用optional()
帮助器。
Move the logic to controller: 将逻辑移动到控制器:
$funds = Fund::with('user')->where('created_at', '>', Carbon::now()->subHours(24))->orderBy('id', 'desc')->take(10)->get();
return view('your.view', compact('funds'));
Then in the view: 然后在视图中:
@foreach ($funds as $fund)
{{ optional($fund->user)->name }}
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.