带有大量联接的laravel查询构建

时间:2019-02-04 19:24:37

标签: mysql laravel

我的SQL查询是

$q = "SELECT 
                file,
                roleId,
                page,
                type,
                userType,
                COUNT(DISTINCT($a)) as 'a',
                COUNT(DISTINCT($b)) as 'b'
            FROM table_name
            WHERE
                course IN ($type)
                AND date BETWEEN '$startDate' AND '$endDate'
                AND (course_1 is NULL OR course_1 NOT IN ('ABCD'))
                AND deleted IS NULL
                AND type LIKE '%Professor%'
                AND action = 'submit'
                GROUP BY file, roleId";

我想将该查询转换为laravel查询生成器,例如

$orders = DB::table('table_name')
                ->select('file', 'roleId', 'page', 'type', userType DB::raw('COUNT(DISTINCT(($a)) as 'a'))
                ->groupBy('file', 'roleId')
                ->get();

了解如何将其他COUNT添加到其中以及如何以及在何处链接-> where()? 有人可以帮忙建立这个吗?

2 个答案:

答案 0 :(得分:0)

<?php 

$orders = DB::table('table_name')
->whereIn('course', $courseTypes)
->whereBetween('date', [$startDate, $endDate])
->where(function($q){
    return $q->whereNull('course_1')
    ->orWhereNotIn('course_1', $courseArrayToFilter);
})
->whereNull('deleted')
->where('type', 'like', '%Professor%')
->where('action', 'submit')
->groupBy('file', 'roleId')
->select(
    'file',
    'roleId',
    'page',
    'type',
    'userType',
    \DB::raw("COUNT(DISTINCT($a)) as a"),
    \DB::raw("COUNT(DISTINCT($b) as b")
)
->get();

答案 1 :(得分:0)

也许以最干净的方式做到这一点:

  • 在调用DB门面的情况下使用Model实例
  • 使用whereRaw传递复杂或纯SQL查询
  • 使用selectRaw()处理诸如COUNT之类的实例函数的纯SQL查询
  • 使用多个WHERE模拟AND运算符
  • 使用whereIn过滤数据范围
  • 您需要GROUP BY SELECT中的所有列这时您遇到了错误,我的意思是您的查询有误

代码

$data = Model::select('file', 'roleId', 'page', 'type', 'userType')
                ->selectRaw('COUNT(DISTINCT($a)) as a')
                ->selectRaw('COUNT(DISTINCT($b)) as b')
                ->whereRaw('type IN $type')
                ->whereIn('date', [$startDate, $endDate])
                ->whereRaw("course_1 IS NULL OR course_1 NOT IN('ABCD')")
                ->whereNull('deleted')
                ->where('type', 'LIKE', "%".'Professor'."%")
                ->where('action', '=', 'submit')
                ->groupBy('file', 'roleId', 'page', 'type', 'userType')
                ->get();