我希望在我的控制器中实现此查询的功能
select * from table where true
if($param1 != ""){
and table.column1 = '$param1'
}
if($param2 != ""){
and table.column2 = '$param2'
}
到目前为止,我所尝试的是
function seachpullethouse(Request $request){
$searchcode = $request->code;
$mpullethouse = DB::table('mpullethouses')->query();
if(!empty($searchcode)){
$query ->Where('mpullethouses.code','like','%'.$searchcode.'%');
}
$query ->select('mpullethouses.*')->get();
return response()->json(['mpullethouse'=>$mpullethouse]);
}
但似乎这是错误的...可以请任何人帮助我吗?? ...
答案 0 :(得分:1)
您可以使用when
。
public function seachpullethouse(Request $request)
{
$searchcode = $request->code;
$mpullethouse = DB::table('mpullethouses')
->when($searchcode, function ($query) use ($searchcode) {
return $query->where('code', 'like', "%{$searchcode}%");
})
->get();
return response()->json(['mpullethouse' => $mpullethouse]);
}
有关详情,请查看https://laravel.com/docs/5.4/queries#conditional-clauses