開發中遇到的一個比較複雜的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 '%機電%')

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