Laravel 8 - Eloquent 关系无法访问关系属性/值

时间:2021-06-01 06:42:12

标签: laravel-8 eloquent-relationship

模型 1:步行

MainWindowViewModel

模型 2:设备

       return $this->belongsTo('App\Models\Device','device_uuid','device_uuid');
   }

在我的索引文件中:

  public function walks() {
        return $this->hasMany('App\Models\Walks','device_uuid','device_uuid');
    }

这会导致错误:

     <table class="table table-bordered">
            <tr>
                <th>No</th>
                <th>Walk Date</th>
                <th>Device Name</th>
                <th>In</th>
                <th>Out</th>
                <th width="280px">Action</th>
            </tr>
            @foreach ($walks as $walk)

            <tr>
                    <td>{{ ++$i }}</td>
                    <td>{{ $walk->walk_datetime }}</td>
                    <td>{{ $walk->device->device_uuid }}</td> <========
                    <td>{{ $walk->walk_in }}</td>
                    <td>{{ $walk->walk_out }}</td>
                    <td>
                        <form action="{{ route('walks.destroy',$walk->id) }}" method="POST">

                            <a class="btn btn-primary" href="{{ route('walks.edit',$walk->id) }}">Edit</a>

                            @csrf
                            @method('DELETE')
                            <button type="submit" class="btn btn-danger">Delete</button>
                        </form>
                    </td>
                </tr>
            @endforeach
        </table>

“试图获取非对象的属性‘device_uuid’”

如果我这样做:

<td>{{ $walk->device->device_uuid }}</td> <========

我明白了:

<td>{{ $walk->device }}</td>

这意味着关系工作正常。

还有其他方法可以用来访问“device_mame”属性吗?

与以下问题相关.. All walks 都有一个有效的设备链接。

  1. 步行列表。这是我打印时显示的 -> $walk->device enter image description here

  2. 步行列表(DB) enter image description here

  3. 设备列表 (DB) enter image description here

1 个答案:

答案 0 :(得分:1)

:) 在我看来,有些 Walks 没有 Device。这就是它(通常)抛出该错误的原因。

Laracasts 上的类似问题。

或者你可以做的是使用三元运算符

<td>{{(isset($walk->device->device_uuid)? $walk->device->device_uuid : ''}}</td>
相关问题