
有時候項目中需要進行多個字段搜索就可以用到此方法
在Laravel中的可以同時使用多個where,所以我們可以每個字段分配一個where()
然后在每個where()中去閉包判斷
$username = '';// 收貨人姓名
$hospital_id = ''; // 醫院id
# 判斷是否有姓名搜索
if (!empty($request->username)) {
$username = $request->username;
}
# 判斷是否有醫院搜索
if (!empty($request->hospital_id)) {
$hospital_id = $request->hospital_id;
}
# 執行
$data = DB::table('test')
->where(function($query)use($username){
# 進行判斷
if (!empty($username)) {
$query->where('username','Like',"%$username%");
}
})
->where(function($query)use($hospital_id){
# 進行判斷
if (!empty($hospital_id)) {
$query->where('hospital_id','=',$hospital_id);
}
})
->get()
->toArray();
dd($data)





