【问题标题】:How to get user's name from user_id in laravel?如何从 laravel 中的 user_id 获取用户名?
【发布时间】:2018-06-30 03:08:46
【问题描述】:

我有 2 个表,第一个 fund 第二个 users 我在 users 表中注册了会员名称,而在 funduser_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'); 
}

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    似乎并非所有资金都已填满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
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 我用过,但它说。试图获取非对象的属性
      • 尝试更新代码,并尝试将您的查询移动到控制器,您不应该在视图模板中查询
      • 然后使用命名空间作为前缀App\Fund::with('user')-&gt;where('created_at', '&gt;', Carbon::now()-&gt;subHours(24))-&gt;orderBy('id', 'desc')-&gt;take(10)-&gt;get()
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-24
      • 2017-02-17
      • 1970-01-01
      • 1970-01-01
      • 2019-08-22
      • 2022-01-23
      • 1970-01-01
      相关资源
      最近更新 更多