带有两个表的laravel连接查询每个都有两个where条件

时间:2018-07-26 08:53:05

标签: php laravel

这是我的控制器,我需要在is_enabled = 0的表章节上添加where条件

 $module = $course->modules()
                    ->with('chapters')
                    ->join('course_student', 'course_student.module_id', '=', 'modules.id')
                    ->select('*', DB::raw('course_student.module_id as id'))
                    ->where('is_enabled', 1)
                    ->where('course_student.student_id', $user->id)
                    ->where('course_student.test_completed', 0)
                    ->where('course_student.ends_on', '>', Carbon::now())
                    ->orderBy('order')
                    ->first();

1 个答案:

答案 0 :(得分:0)

如果要有条件地选择关系,则应使用whereHas方法。

  

这些方法允许您将自定义约束添加到   关系约束,例如检查评论内容

Relationships documentation

为您提供类似的代码:

$module = $course->modules()
    ->whereHas('chapters', function ($query) {
        $query->where('is_enabled', 0);
    })
    ->join('course_student', 'course_student.module_id', '=', 'modules.id')
    ->select('*', DB::raw('course_student.module_id as id'))
    ->where('is_enabled', 1)
    ->where('course_student.student_id', $user->id)
    ->where('course_student.test_completed', 0)
    ->where('course_student.ends_on', '>', Carbon::now())
    ->orderBy('order')
    ->first();
相关问题