我正在使用 Laravel 5.3 开发一个 Web 应用程序。我现在遇到了 Laravel 查询生成器方法的问题,
whereIn
。
我有这样的桌子。
student - id, name, dob
course - id, code
student_course - student_id, course_id
我想做的是让学生通过student_course表的
course_id
进行搜索,而不加入任何表。在手动查询中,我确实喜欢这样。
SELECT * FROM `student` WHERE `student`.`id` IN (SELECT `student_id` FROM `student_course` WHRE `course_id`= ?)
所以现在当我尝试将其转换为 Laravel 查询生成器时,我遇到了问题。这是我的代码:
DB::table('student')->whereIn('id',[ "Here I want to run sub query" ])->get();
正如您在
whereIn()
的第二个参数中看到的那样,我遇到了问题。在这种情况下,我需要运行原始查询吗?如何运行原始查询作为第二个参数?如果没有,我如何才能像上面这样在一个查询中按 course_id
进行过滤而不加入任何表?
参考这个
$courseId = 1;
$data = DB::table('student')->whereIn('id',function($query) use (courseId){
$query->select('student_id')
->from('student_course')->where('course_id', '=',$courseId);
})->get();
如果你想通过模型,你可以使用:
$res = Student::whereIn('id',StudentCourse::where('course_id',$course_id)->pluck('student_id')->toArray())->get();
你可以这样做:
DB::table('student')
->whereRaw("id IN (SELECT `student_id` FROM `student_course` WHERE `course_id`= ?)", [$course_id])
->get();
对于谁使用查询生成器:
$data = DB::table('student')
->whereIn('id',DB::table('student_course')
->where('course_id','=',$courseId)
->pluck('student_id')
->toArray())
->get();