我想获取相关/嵌套对象的属性。问题对象有很多选择,并且我想返回一个具有等于True/1的correct
字段的某个选项。获取相关/嵌套对象的属性
所以我由ID获得这样的问题:
$question = Question::find($request->get('id'));
然后得到具有正确== 1相关的选择:
$answer = $question->choice->where('correct', 1);
return $answer;
的响应是一个阵列内的对象:
[
2
{
"id": 3,
"choice": "Non eos architecto ut.",
"question_id": 1,
"correct": 1,
}
]
我想访问选择字段:
return $answer->choice;
但得到这个错误:
Undefined property: Illuminate\Database\Eloquent\Collection::$choice
我试着用压平:
$answer = $question->choice->where('correct', 1)->flatten();
但所有这样做是删除的问题ID 2
,但不允许我进入对象属性。