【问题标题】:'Trying to get property 'value_type1' of non-object' in laravel'试图在 laravel 中获取非对象的属性'value_type1'
【发布时间】:2026-01-07 10:35:01
【问题描述】:

我在函数中运行以下查询: $sensor = Sensor::where('id', $measurement->sensor_id)->with('sensorType', 'sensorType.valueType1', 'sensorType.valueType2')->first();

这将返回以下响应:

{
    "id": 1,
    "name": "DHT22 Kantoor",
    "sensor_type_id": 1,
    "active": 1,
    "organisation_id": 1,
    "disabled_until": null,
    "created_at": null,
    "updated_at": "2020-07-15T11:12:33.000000Z",
    "sensor_type": {
      "id": 1,
      "name": "DHT22",
      "value_1_type_id": 1,
      "value_2_type_id": 2,
      "created_at": null,
      "updated_at": null,
      "value_type1": {
        "id": 1,
        "name": "Temperatuur",
        "unit": "°C",
        "created_at": null,
        "updated_at": null
      },
      "value_type2": {
        "id": 2,
        "name": "Luchtdruk",
        "unit": "Pa",
        "created_at": null,
        "updated_at": null
      }
    }

我正在尝试通过以下方式获取此响应中的“温度”:

$affValue = $sensor->sensor_type->value_type->name;

但这给了我以下错误: Trying to get property 'value_type1' of non-object

我已尝试执行以下操作: $sensor->name 返回DHT22 Kantoor $sensor->sensor_type->id 给出与以前相同的错误

我是否试图错误地访问此值?还是有不同的解决方案?

【问题讨论】:

  • 试试dd($sensor->sensor_type);,你会得到什么?
  • @aynber 这将返回 null
  • @aynber 我想通了,现在写一个答案

标签: php laravel eloquent laravel-7.x


【解决方案1】:

我现在开始工作了。 而不是使用sensor_type 我需要使用sensorType value_type1 也一样,必须是 valueType1 因此,您需要使用 App\SensorType 中的名称,而不是使用响应中的名称。

【讨论】: