开发中遇到的一个比较复杂的SQL语句,Laravel框架中的sql语句写法和原始sql的对应关系。

  1. Select * from a left join b on a.x = b.y where col = 0 and col1 = 1 and (col2 = 2 or col3 = 3);

Laravel中sql语句和原始sql的对应关系为:颜色相同。

从request中获取参数:$years,$positon,$level_cate。
    $whereArray=[]; //将 值 不为 null 和  "" 的 条件 封装进 数组中 当作 查询条件 
    if($years!=''&&$years!=null){
        array_push($whereArray,['year',$years]);
     }
    if($positon!=''&&$positon!=null){
        array_push($whereArray,['sheng',$positon]);
     }
     if($level_cate!=''&&$level_cate!=null){
        array_push($whereArray,['cengci','like','%'.$level_cate.'%']);
     }

$infoes = DB::table('selected_subjects')
    ->leftJoin('school_infos','selected_subjects.schoolname','=','school_infos.xuexiao')
    ->where($whereArray)     
    ->where(function ($query)use($keyword){
                        $query->where('category','like','%'.$keyword.'%')
                   ->orWhere('major','like','%'.$keyword.'%');
                })->paginate($numberOfPage);

 

转换成 标准的 Sql语句就是: 

 

select * from selected_subjects 
left join school_infos on selected_subjects.schoolname=school_infos.xuexiao 
where year='2019' and sheng='北京' and cengci='本科' 
and (selected_subjects.category like '%机电%' or selected_subjects.major like '%机电%')

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章