laravel - Laravel关系有很多不起作用

标签 laravel error-handling relationships

我想通过在存储用户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

关于laravel - Laravel关系有很多不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50871641/

相关文章:

rest - 在 Laravel 5.3 中找不到带有 PUT 请求的正文数据

php - 如何获取错误代码的文本?

javascript - 如何通过 npm jquery-ui-datepicker-with-i18n 导入到 laravel?

php - 如何在 laravel 中运行特定的迁移

php - 为什么 "between"在 laravel 计划任务中不可用?

python - 在Heroku上的python worker进程中使用try语句来处理由于对等错误而导致的连接重置是否理想?

python - 你如何在 Python 中测试 file.read() 错误?

ios - 核心数据关系(快速)

mysql - Yii2、ActiveQuery、subQuery 没有带 ID 的条目