【问题标题】:Laravel 8 - Eloquent Relationship cannot access relation properties / valuesLaravel 8 - 雄辩的关系无法访问关系属性/值
【发布时间】:2021-06-01 06:42:12
【问题描述】:

模型 1:步行

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

模型 2:设备

  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>

这会导致错误:

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

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

如果我这样做:

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

我明白了:

{"id":1,"device_uuid":"1902101300368","device_name":"Test 1","created_at":null,"updated_at":null}

这意味着关系正确。

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

与以下问题相关.. All walks 已链接有效设备。

  1. 步行名单。这就是我打印 -> $walk->device 时显示的内容

  2. 步行列表 (DB)

  3. 设备列表 (DB)

【问题讨论】:

  • 您确定循环中的每个Walk 都有一个关联的Device
  • 是的,请看附件。

标签: laravel-8 eloquent-relationship


【解决方案1】:

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

Laracasts 上的类似问题。

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

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

【讨论】:

  • 不幸的是看起来不是这个问题。正如您在图片中看到的那样,我附加了所有记录。
  • 最终上述方法奏效了。非常感谢!
猜你喜欢
  • 2020-12-13
  • 1970-01-01
  • 1970-01-01
  • 2019-03-17
  • 2014-10-18
  • 1970-01-01
  • 2015-03-14
  • 2018-11-28
相关资源
最近更新 更多