Postgres和Laravel搜索查询
我有一个针对多个搜索的查询,问题在于其中一个搜索,我从中得到了正确的结果,但与其他搜索相结合,我对其余字段得到了错误的响应Postgres和Laravel搜索查询,laravel,postgresql,Laravel,Postgresql,我有一个针对多个搜索的查询,问题在于其中一个搜索,我从中得到了正确的结果,但与其他搜索相结合,我对其余字段得到了错误的响应 //I get the correct result for first if, but the second one returns a wrong response. if ($request->has('search_fullname') && !is_null($request->search_fullname)) {
//I get the correct result for first if, but the second one returns a wrong response.
if ($request->has('search_fullname') && !is_null($request->search_fullname)) {
$query->where('full_name', 'ILIKE', $request->search_fullname . '%')
->orWhere('full_name', 'ILIKE', '% ' . $request->search_fullname . '%');
}
if ($request->has('search_gender') && !is_null($request->search_gender)) {
$query->where('gender', '=', $request->search_gender);
} //like this if I have many more, the problem is strict from the first one
首先,当您应用
where(A)->或where(B)
查询并应用新的where(C)…
方法时,它将变成:
其中(A和C以及D…)或B
你需要把它改成
其中(A或B)和C与D。。。。
因此,第一个查询需要如下所示:
如果($request->has('search\u fullname')&&!is\u null($request->search\u fullname)){
$query->where(函数($q){
$q->where('full_name','ILIKE',$request->search_fullname.%'))
->或where('full_name'、'ILIKE'、'%'.$request->search_full name'.%');
})
}
其次,您可以使用as-condition方法,它将仅在请求字段不为空时应用于查询
$query->when($request->input('search\u fullname')、函数($q)use($request){
$q->where(函数($q){
$q->where('full_name','ILIKE',$request->search_fullname.%'))
->或where('full_name'、'ILIKE'、'%'.$request->search_full name'.%');
});
})->当($request->input('search_gender')时,函数($q)使用($request){
$q->where('gender','=',$request->search_gender);
});