Laravel HasOne关联返回null或Undefined property错误 如何直接返回指定字段值
错误原因
你之前的写法报错,本质是因为关联方法必须返回Illuminate\Database\Eloquent\Relations\Relation类型的实例,不能直接返回数组/字段值,否则预加载($with属性)调用关联方法时无法执行后续的查询约束逻辑,就会触发addEagerConstraints()相关错误。
实现方案
要保持原有调用格式不变,用Eloquent访问器+重命名关联的方式实现即可,具体代码如下:
// 预加载改名后的关联,避免N+1查询问题 protected $with = ["stepsRelation"]; // 原来的steps关联改名为stepsRelation,仅用来做关联查询 public function stepsRelation() { return $this->hasOne("App\Compares\ComparesSteps", "compare_id", "id"); } // 定义steps访问器,直接返回关联表中的steps字段值 public function getStepsAttribute() { // 关联不存在时返回空数组,也可根据需求修改为返回null return $this->stepsRelation?->steps ?? []; } // 可选配置:让steps字段在模型转数组/JSON时自动输出 protected $appends = ['steps']; // 可选配置:隐藏原始关联对象,不输出到数组/JSON中 protected $hidden = ['stepsRelation'];
修改完成后,上层业务调用$model->steps或者模型转数组、JSON时,输出格式和表拆分前完全一致,无需调整原有业务代码。
效果验证
修改后模型转数组的结果和预期完全匹配:
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" => [] ]
内容的提问来源于stack exchange,提问作者YaBCK
相关产品推荐
相关产品推荐

