%like%query不按预期给出结果

时间:2017-01-21 12:03:16

标签: php sql laravel search laravel-5.3

我正在研究搜索功能,我正在根据用户输入查询,但我没有按预期得到结果

//if user searches walter getting proper response

http://localhost:8000/api/v1/search/walter  

{
  "data": [
    {
      "id": 1,
      "first_name": "Walter",
      "last_name": "White",
      "phone_number": "9665885542",
      "registration_id": "12345b67892"
    },
    {
      "id": 8,
      "first_name": "Mitty",
      "last_name": "Walter",
      "phone_number": "8826835542",
      "registration_id": "dffdfg54ty45y"
    }
  ]
}

// but if user searches walt the response is

http://localhost:8000/api/v1/search/walt  

{
  "data": []
}

我的方法

//搜索驱动程序 public function getSearchResults($ search_input){

$search_drivers = Driver::where('id', 'like', $search_input)
                 ->orWhere('first_name', 'like', $search_input)
                 ->orWhere('last_name', 'like', $search_input)
                 ->orWhere('phone_number', 'like', $search_input)
                 ->orWhere('registration_id', 'like', $search_input)
                 ->select('id','first_name','last_name','phone_number','registration_id')
                 ->get();

return Response::json([
    'data' => $search_drivers
]);     

}

在输入完整数据之前有没有更好的方法来获得结果

谢谢

1 个答案:

答案 0 :(得分:1)

like的正确语法是'%'.$search_input.'%'

$search_drivers = Driver::where('id', 'like', '%'.$search_input.'%')
     ->orWhere('first_name', 'like', '%'.$search_input.'%')
     ->orWhere('last_name', 'like', '%'.$search_input.'%')
     ->orWhere('phone_number', 'like', '%'.$search_input.'%')
     ->orWhere('registration_id', 'like', '%'.$search_input.'%')
     ->select('id','first_name','last_name','phone_number','registration_id')
     ->get();