如何在Laravel中通过用户ID获取用户名称?

4

我有两张表,第一张是fund,第二张是users。我已经在users表中注册了会员名字,在fund表中也有已注册会员的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

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

我已经使用了,但它显示“尝试获取非对象的属性”。 - Waqar Ali
尝试使用更新后的代码,并尝试将查询移动到控制器中,不应在视图模板中进行查询。 - Sohel0415
然后使用命名空间前缀为 App\Fund::with('user')->where('created_at', '>', Carbon::now()->subHours(24))->orderBy('id', 'desc')->take(10)->get() - Sohel0415

0

看起来并不是所有的资金都填写了user_id。在这种情况下,您应该使用{{link1: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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接