0

我正在尝试使用hasOne在我的数据集中返回单个值,但是如果不返回完整对象,我似乎无法将单个列作为值返回。

返回时对象的外观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" => []
]

返回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" => []
    ]

返回Call to a member function addEagerConstraints() on array

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

返回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().

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

4

1 回答 1

1

使用使用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");
    }
}

在appends 上查看Laravel 文档

于 2021-10-08T12:31:32.510 回答