HasOne 显示 "null" 或 "Undefined property: Illuminate\Database\Eloquent\Relations\HasOne"

HasOne showing either "null" or "Undefined property: Illuminate\\Database\\Eloquent\\Relations\\HasOne"

我正在尝试使用 hasOne 到 return 我的数据集中的单个值,但是我似乎无法 return 单个列作为没有 return完整对象。

当您 returned 时对象看起来像什么 return hasOne:

protected $with = ["steps"];

public function steps() {
    return $this->hasOne("App\Compares\ComparesSteps", "compare_id", "id");
}

仅使用 hasOne 作为默认对象的结果:

array:21 [
  "id" => 5887894545
  "steps" => array:5 [
    "id" => 21
    "compare_id" => 588789
    "steps" => array:12 [
      0 => 1
      1 => 2
      2 => 3
      3 => 4
      4 => 13
      5 => 6
      6 => 7
      7 => 17
      8 => 8
      9 => 9
      10 => 10
      11 => 12
    ]
    "created_at" => "2021-10-05 08:48:44"
    "updated_at" => "2021-10-05 08:48:44"
  ]
  "created_at" => "2021-10-05 08:48:43"
  "updated_at" => "2021-10-05 08:48:43"
  "expired_at" => "2021-10-09 08:48:43"
  "booked" => 0
  "reference" => null
  "utm" => ""
  "updates" => []
]

Returns null:

   array:21 [
      "id" => 5887894545
      "steps" => null
      "created_at" => "2021-10-05 08:48:43"
      "updated_at" => "2021-10-05 08:48:43"
      "expired_at" => "2021-10-09 08:48:43"
      "booked" => 0
      "reference" => null
      "utm" => ""
      "updates" => []
    ]

Returns Call to a member function addEagerConstraints() on array:

public function steps() {
    return $this->hasOne("App\Compares\ComparesSteps", "compare_id", "id")->value("steps");
}

Returns Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$steps:

public function steps() {
    return $this->hasOne("App\Compares\ComparesSteps", "compare_id", "id")->steps;
}

预期结果:

   array:21 [
      "id" => 5887894545
      "steps" => array:12 [
          0 => 1
          1 => 2
          2 => 3
          3 => 4
          4 => 13
          5 => 6
          6 => 7
          7 => 17
          8 => 8
          9 => 9
          10 => 10
          11 => 12
      ]
      "created_at" => "2021-10-05 08:48:43"
      "updated_at" => "2021-10-05 08:48:43"
      "expired_at" => "2021-10-09 08:48:43"
      "booked" => 0
      "reference" => null
      "utm" => ""
      "updates" => []
    ]

根据与@MaartenDev 评论中的对话进行更新

我想在调用模型时将 $model->steps->steps 附加到 $model->steps。因为我正在更新数据库表以将某些数据拆分到表中,并希望在调用模型时保持数据结构相同。

例如如果您使用的是 getUserCountAttribute,您可以通过 hasMany()->Count().

轻松地 return 只是数字

所以我想在调用模型时将 steps 数组附加到 steps 属性。

是否可以选择使用使用 steps 关系的自定义 getter?您可以使用 $appends.

预加载值
class Model {
    protected $appends = ["steps"];
    protected $hidden = ['stepsRelation']

    public function getStepsAttribute()
    {
        return $this->stepsRelation->steps;
    }
    
    private function stepsRelation() {
        return $this->hasOne("App\Compares\ComparesSteps", "compare_id", "id");
    }
}

查看 Laravel docs on appends