我想通过在存储用户ID的'finished_by'列中找到它来打印用户名。但我得到这个错误:



库存模型的finished_by具有用户ID。

这是我的blade.php

@foreach($inventories as $inventory)
    <tr>
      <td>{{$inventory['id']}}</td>
      <td>{{$inventory->user->name}}</td>
    </tr>
@enforeach

和我的索引方法
$company_id = Auth::user()->company_id;
$inventories = Inventory::where('company_id',$company_id)->get();

return view('inventories', compact('inventories', 'companies'));

和我的关系

Inventory.php
public function users(){
    return $this->belongsTo(User::class, 'finished_by');
}

User.php
public function inventories(){
    return $this->hasMany(Inventory::class, 'finished_by');
}

最佳答案

首先更改您的关系

Inventory.php

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

User.php
public function inventories(){
    return $this->hasMany("App\Inventory", 'finished_by');
}

您需要在急切加载中添加user关系
$inventories = Inventory::where('company_id',$company_id)->with('user')->get();


@foreach($inventories as $inventory)
    <tr>
        <td>{{$inventory->id}}</td>
        <td>
           @if($inventory->user)
              {{$inventory->user->name}}
           @else
              'No User'
           @endif
        </td>
    </tr>
@enforeach

10-08 08:43
查看更多