简体   繁体   English

在with()上添加where()以便加载。

[英]Adding where() on with() eager loading.

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 , 首先,我有3个模型, CourseStudentQuiz

  • 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. 我想这样做,因为我只想获取与Student模型和Course模型都相关的测验。

To give you the full picture , after that I loop through the $students variable in a vue component like this: 为了给您提供完整的图片 ,之后,我在vue组件中遍历$students变量,如下所示:

<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. 我正在使用Student模型,因为我也在检索测验以外的其他属性。

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 . 但是,当然,当我像那里的查询一样执行操作时,我最终会为所有具有course_id = $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. 我想筛选的结果,得到学生的测验, 只有当他们有一个course_id无论当前课程的id是。

You can use whereHas function to do your job, something like this: 您可以使用whereHas函数来完成工作,如下所示:

$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. 我认为,如果您遵循惯例,则应与students一起进行Quiz模型,并交叉检查course ,这取决于您。 You can find out more on Laravel Documentation Hope this resolves your problem. 您可以在Laravel文档中找到更多信息。希望这可以解决您的问题。

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM