在这种情况下如何动态更改SQL查询?

时间:2017-05-11 10:45:08

标签: php laravel

我有一个控制器,根据网址'请求'参数,返回SQL查询。

switch ($request->get('request')){
        case '3dvideo':
            $students = Student::orderBy('year', 'desc')->where('orientation', '3D')->inRandomOrder()->paginate(12);
            break;
        case '2d':
            $students = Student::orderBy('year', 'desc')->where('orientation', '2D')->inRandomOrder()->paginate(12);
            break;
        case 'web':
            $students = Student::orderBy('year', 'desc')->where('orientation', 'web')->inRandomOrder()->paginate(12);
            break;
        case 'all':
            $students = Student::orderBy('year', 'desc')->inRandomOrder()->paginate(12);
            break;
        default:
            $students = Student::orderBy('year', 'desc')->inRandomOrder()->paginate(12);
            break;
    }

现在我的URL(年份)中有第二个参数,我不知道如何根据这两个参数(如果存在年份),我返回一个这样的SQL查询:

$students =  Student::orderBy('year', 'desc')->where('orientation', 'web')->where('year', 'MY-YEAR')->inRandomOrder()->paginate(12);

非常感谢

2 个答案:

答案 0 :(得分:1)

您可以这样做:

$students = Student::query();

if (in_array($request->request, ['3dvideo', '2d', 'web'])) {
    $students = $students->where('orientation', $request->request);
}

if ($request->has('year')) {
    $sudents = $students->where('year', $request->year);
}

$students = $students->latest('year')->inRandomOrder()->paginate(12);

答案 1 :(得分:1)

  

优化这样的查询。

  $query = Student::orderBy('year', 'desc')->inRandomOrder();

     if($request->has('orientation')){
           query->where('orientation',$request->get('orientation'));
     }

    if($request->has('year')){
           query->where('year',$request->get('year'));
     }
  $student = $query->paginate(12);