我打算隨機化我對 quiz_question 和選擇的查詢順序,但 quiz_question 是唯一一個隨機化的,但選擇仍然相同。
這是我的代碼:
class QuestionByQuizID extends Controller
{
public function index(int $quiz_id){
$questions = quizQuestions::where('quiz_id', '=', $quiz_id)->with(['choices'])->inRandomOrder()->get();
if(is_null($questions)){
return response()->json('Record not found!', 401);
}
return response(['message'=>"Questions displayed successfully",
'quizQuestions'=>$questions],200);
}
}
這是使用郵遞員的示例查詢
"message": "Questions displayed successfully",
"quizQuestions": [
{
"id": 580,
"quiz_id": 36,
"question_num": 10,
"question_content": "What Are Those",
"correct_answer": null,
"created_by": null,
"updated_by": null,
"created_at": "2022-01-12T12:58:27.000000Z",
"updated_at": "2022-01-12T12:58:27.000000Z",
"question_image": null,
"tagalog_question": "Ano yan!",
"choices": [
{
"id": 1861,
"quiz_questions_id": 580,
"option": "choice 1",
"remarks": 0,
"created_at": "2022-01-12T12:58:27.000000Z",
"updated_at": "2022-01-12T12:58:27.000000Z",
"choices_image": null,
"tagalog_choices": "tagalog"
},
{
"id": 1862,
"quiz_questions_id": 580,
"option": "choice2",
"remarks": 0,
"created_at": "2022-01-12T12:58:27.000000Z",
"updated_at": "2022-01-12T12:58:27.000000Z",
"choices_image": null,
"tagalog_choices": "tagalog"
},
{
"id": 1863,
"quiz_questions_id": 580,
"option": "choice3",
"remarks": 0,
"created_at": "2022-01-12T12:58:27.000000Z",
"updated_at": "2022-01-12T12:58:27.000000Z",
"choices_image": null,
"tagalog_choices": "tagalog"
},
{
"id": 1864,
"quiz_questions_id": 580,
"option": "choice4",
"remarks": 1,
"created_at": "2022-01-12T12:58:27.000000Z",
"updated_at": "2022-01-12T12:58:27.000000Z",
"choices_image": null,
"tagalog_choices": "tagalog"
}
]
誰能幫我?提前致謝。
uj5u.com熱心網友回復:
您可以為關系做額外的查詢條件choices:
$questions = quizQuestions::where('quiz_id', '=', $quiz_id)->with(['choices' => function($query){
$query->inRandomOrder();
}])->inRandomOrder()->get();
https://laravel.com/docs/8.x/eloquent-relationships#constraining-eager-loads
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/411079.html
標籤:
下一篇:驗證規則,三個欄位之一是必需的
