【发布时间】:2021-06-20 23:58:13
【问题描述】:
My Relationship is
public function QuestionOptions()
{
return $this->hasMany('App\Models\QuestionOption','QuestionId');
}
but when i am running this query
$builder = Question::select([
'id', 'type', 'questionText', 'note', 'solutionText',
])->with('QuestionOptions')
->orderByRaw("RAND()")
->skip(0)
->take(1)
->get()
->toArray();
i am getting this
{
"id": 1,
"type": "multiple",
"questionText": "2 + 2 = ?",
"note": null,
"solutionText": null,
"question_options": []
},
so i want to know why i am getting question_options empty is there any problem in my query?
更改后:-
我尝试更改我的查询并删除了选择,所以现在我的查询看起来像这样
$builder = Question::with('QuestionOptions')
->orderByRaw("RAND()")
->skip(0)
->take(1)
->get()
->toArray();
运行查询后,我的输出如下所示,我得到了两个表的所有字段,这没问题,但现在出现了问题,我应该如何只获取特定字段
[{
"Id": 2,
"UID": "123456789098765",
"Type": "single",
"Rank": 2,
"QuestionText": "4 + 4 = ?",
"TotalMarks": 5,
"Note": null,
"SolutionText": null,
"Status": "active",
"TimeStamp": "2020-11-17 12:04:18",
"NegativeMark": 2,
"TestId": 4,
"question_options": [
{
"Id": 13,
"OptionText": "5",
"Rank": 1,
"IsAnswer": "no",
"Status": "deactive",
"TimeStamp": "2020-11-17 12:59:14",
"QuestionId": 2
},]
【问题讨论】:
-
迁移是什么样的?问题和/或 question_options 的外键字段的名称是什么?
-
我的问题表包含 -> id,type,rank,questionText,totalMarks,status,testId 我的 questionOption 表包含 -> id,optionText,rank,IsAnswer,status,questionId
标签: sql laravel eloquent relationship has-many