Laravel-如何从另一个关系表获取数据

时间:2019-01-25 04:45:06

标签: php laravel laravel-5.2

我有4张这样的桌子:

quizzes
id | title

questions
id | question

question_quiz
id | quiz_id | question_id

question_options
id | question_id | option | is_answer

测验模型

/**
 * Get the questions for the quiz.
 */
public function questions()
{
    return $this->belongsToMany('App\Question');
}

问题模型

/**
 * Get the question options for the question.
 */
public function question_options()
{
    return $this->hasMany('App\QuestionOption');
}

测验表如何从question_options表中检索数据?

2 个答案:

答案 0 :(得分:0)

如果您的测验模型名称为测验,那么这可能会对您有所帮助。这将为您提供与测验有关的所有相关选项。

Quiz::with('questions.question_options')->get(); 

答案 1 :(得分:0)

Quiz::with('questions.question_options')->where('status', 'ACTIVE')->get();

使用它可以获取问题和该问题的question_options

响应将是

[
    {
        id: 1,
        title: quiz,
        questions: [{
            id: 1,
            question: question,
            question_options: [
                {
                    id: 1,
                    question_id: question,
                    option: option 1
                    is_answer: 1
                },
                {
                    id: 2,
                    question_id: question,
                    option: option 2
                    is_answer: 0
                },
                {
                    id: 3,
                    question_id: question,
                    option: option 3
                    is_answer: 0
                },
            ]
        }]
    }
]