Laravel 关系 hasMany 无效

Laravel relationship hasMany not working

我想通过在存储用户 ID 的 'finished_by' 列中查找来打印用户名。但我收到此错误:

Trying to get property 'name' of non-object

库存模型有 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();

Now Template Rendering

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

我不确切知道你有哪些字段,但请测试此代码:

@foreach($inventories as $inventory)
    <tr>
        <td>id : {{$inventory['id']}}</td>
        <td>name : {{$inventory->users->toArray()['name']}}</td>
    </tr>
@endforeach

那是因为您在 Inventory 模型中定义了 users 但您在 blade 文件中调用了 user 因此您必须更改您的作用于:

public function user(){
    return $this->belongsTo(User::class, 'finished_by');
}

更新控制器代码//你需要添加关系

$inventories = Inventory::where('company_id',$company_id)->with('user')->get();
$company_id = Auth::user()->company_id;
$inventories = Inventory::where('company_id',$company_id)->get();

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