如何将其转换为laravel查询生成器格式?

时间:2019-07-30 00:11:06

标签: sql laravel join subquery query-builder

我有一个使用常规sql表示法的查询,但是很难将其转换为laravel构建器表示法。

查询:

SELECT Course.CourseName
     , SUM(CASE WHEN StudentID <> 0 THEN 1 ELSE 0 END) As InClass
     , Instructor.InstructorFirstName
     , ProgramName
     , SemesterTaught
 FROM program
      JOIN course
        ON program.ProgramID = course.ProgramID
      JOIN (SELECT CourseID
                 , SemesterTaught 
              FROM classtime 
            GROUP BY CourseID, SemesterTaught) AS classtime
        ON course.CourseID = classtime.CourseID
      LEFT JOIN (SELECT InstructorID
                      , CourseID
                      , StudentID 
                   FROM enrolled) AS enrolled
             ON classtime.CourseID = enrolled.CourseID
      LEFT JOIN instructor
             ON enrolled.InstructorID = instructor.InstructorID
GROUP BY CourseName, InstructorFirstName, SemesterTaught, ProgramName 

我尝试过的事情:

DB::table('programs')
->select('courses.CourseName', 'SUM(CASE WHEN StudentID <> 0 THEN 1 ELSE 0 END AS StudentsInClass', 'instructors.InstructorFirstName', 'ProgramName', 'SemesterTaught')
->join('courses', 'programs.ProgramID', '=', 'course.ProgramID')
->join(DB::raw('(SELECT CourseID, SemesterTaught FROM classtimes GROUP BY CourseID, SemesterTaught) AS classtimes'), 'courses.CourseID', '=', 'classtimes.CourseID')
->leftJoin(DB::raw('(SELECT InstructorID, CourseID, StudentID FROM enrolleds) AS enrolled'), 'classtimes.CourseID', '=', 'enrolled.CourseID')
->leftJoin('instructors', 'enrolled.InstructorID', '=', 'instructors.InstructorID')
->groupBy('courses.CourseName', 'instructors.InstructorFirstName', 'SemesterTaught', 'ProgramName')->get(); 

我想使用laravel查询构建器语法实现此查询,并尽可能避免使用DB :: raw。我还试图找出如何在我的选择原因中使用聚合函数,而不会出现“列不存在错误”。

1 个答案:

答案 0 :(得分:1)

想出了使查询正常工作的答案,如果以后有人看到这样的话:

moveToFirst