添加where()on()急切加载。

I have a little but intricate problem here, I'll try to explain it as best I can.

First I have 3 models, Course, Student, and Quiz,

  • Student and Course are in a Many to Many relationship
  • Student and Quiz are in a Many to Many relationship
  • Quiz and Course are in a One to Many relationship respectively

And I have this following query:

 $course = Course::whereSlug($slug)->first(); // Some Course

 $quizzes = $course->students()->with('quizzes'); // <-- Here lies the problem.

In the last sentence I want to edit this query to be something like this:

 $quizzes = $course->students()->with('quizzes)->where('course_id', $course->id);

I want to do it like that because I want to only grab the quizzes that are related to both the Student model and the Course model.

To give you the full picture, after that I loop through the $students variable in a vue component like this:

<div v-for="student in students"></div>

I am looping with the Student model Because I'm also retrieving different properties other than the quizzes.

But of course when I do it like the query up there I end up retrieving all quizzess for the all students that has a course_id = $course_id.

Required

I want to filter the results to get the quizzes of a student ONLY if they have a course_id of whatever the current courses's id is.

You can use whereHas function to do your job, something like this:

$quizzes = $course
        ->students()
        ->whereHas('quizzes', function($q){
            $q->where('course_id', $course->id);
        })
        ->with('quizzes)
        ->get();

I think if you follow the convention you should take Quiz model with students and course cross checked, its upto you. You can find out more on Laravel Documentation Hope this resolves your problem.

Of course after I posted the question I found the answer online randomly, here it is:

$quizzes = $course->students()->with(['quizzes'=> function($query) use ($course) {
              $query->where('course_id', $course->id);
           }])->get();