如何从laravel中的user_id获取用户名?

时间:2018-01-21 09:32:46

标签: php laravel laravel-5

我有2个表1st fund 2nd users我在注册会员的usersfund中的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>

我已将以下代码粘贴到我的基金模型中。但它没有用。

public function user(){
    return $this->belongsTo('App\User', 'user_id'); 
}

2 个答案:

答案 0 :(得分:0)

使用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

答案 1 :(得分:0)

看起来并非所有资金都填充了user_id。在这种情况下,您应该使用optional()帮助程序。

将逻辑移至控制器:

$funds = Fund::with('user')->where('created_at', '>', Carbon::now()->subHours(24))->orderBy('id', 'desc')->take(10)->get();
return view('your.view', compact('funds'));

然后在视图中:

@foreach ($funds as $fund)
    {{ optional($fund->user)->name }}
@endforeach
相关问题