Laravel : 如何随机选择测验的查询

Laravel : How to randomize the query of the Quiz with choices

我打算随机化我对 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);
}

}

这是使用 postman 的示例查询

"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"
            }
        ]

谁能帮帮我?提前致谢。

可以为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