三个外键BelongsToMany Relations在Laravel中返回null

时间:2016-04-15 19:21:36

标签: laravel-5 eloquent has-and-belongs-to-many

我正在使用多个外键Laravel 5 Eloquent实现数据透视表。 已经阅读了这些链接

我的表格如下: -

Quizzes
-Id
-Name

Sections
-Id
-Name

Quiz_Section
-Section_id
-Quiz_Id
-Max_Marks
-Max_Questions

Questions
-Id
-Description

Quiz_Section_Question
-Quiz_id
-Section_Id
-Question_Id

模态 -

测验模态

public function sections()
{
    return $this->belongsToMany('App\Section', 'quiz_section', 'quiz_id', 'section_id')->withPivot('max_questions','max_marks');
}

public function sectionsWithName()
{
    return $this->hasMany('App\QuizSection','quiz_id', 'id')
    ->join('sections', 'quiz_section.section_id', '=', 'sections.id')
    ->selectRaw('quiz_id, section_id, sections.name, max_questions, max_marks');
}   

部分模态

public function quizzes()
{
    return $this->belongsToMany('App\Quiz', 'quiz_section', 'section_id', 'quiz_id')->withPivot('max_questions','max_marks');
}

public function questions()
{
    return $this->belongsToMany('App\Question','quiz_section_question', 'section_id','question_id')->withPivot('quiz_id');
}

QuizSection模式

protected $table = 'quiz_section';


public function Quiz()
{
     return $this->belongsTo('App\Quiz');
}

public function questions()
{
    return $this->belongsToMany('App\Question','quiz_section_question', 'section_id','question_id')->withPivot('quiz_id');
}   

现在我希望所有部分都附有名称和问题,并附加到特定测验的这些部分。

将提供所需输出的SQL查询 -

SELECT quizzes.name, sections.name, quiz_section.max_marks, quiz_section.max_questions,questions.description FROM quizzes 
INNER JOIN quiz_section ON quizzes.id = quiz_section.quiz_id
INNER JOIN sections ON sections.id = quiz_section.section_id
INNER JOIN quiz_section_question ON (quiz_section_question.quiz_id = quizzes.id AND quiz_section_question.section_id=sections.id)
INNER JOIN questions ON questions .id = quiz_section_question.question_id;

我想用Eloquent和Relationships来做。 我尝试了以下代码: -

 $quiz = \App\Quiz::with('sectionsWithName.questions')->where('name','practice paper')->first();
 dd($quiz->sectionsWithName[0]->questions()->toSql());

输出: - 一切都很好,但问题集合是空的。

"select * from `questions` inner join `quiz_section_question` on `questions`.`id` = `quiz_section_question`.`question_id` where `quiz_section_question`.`section_id` is null"

请提出宝贵的建议。

修改: - " Section.Questions"关系返回所有问题。

 $quiz = \App\Quiz::with('sections.questions')->where('name','practice paper')->first();
 dd($quiz->sections[0]->questions()->toSql());

但是我想根据测验& amp;两个部分。

0 个答案:

没有答案