使用一个或多个搜索词构建自动完成服务

Build an auto completion service with one or multiple search terms

我正在为我的移动应用构建自动完成功能。结果需要来自我在 Laravel 5.8.

上构建的 Web 服务

api.php:

Route::get('locations/autocomplete', 'LocationsController@autocomplete');

位置控制器:

public function autocomplete(Request $request)
{
    $locations = Location::query();
    foreach($request->words as $word) {
        $locations->whereRaw('country_name LIKE ? OR state_name LIKE ? OR city_name LIKE ? ', ['%'.$word.'%','%'.$word.'%','%'.$word.'%']);
    } 
    $locations = $locations->distinct()->paginate(10);

    return AutoCompleteLocationResource::collection($locations);
}

当我向 localhost:8000/api/locations/autocomplete?words[]=united&words[]=atlanta 发出 GET 请求时,它给我的结果就像我使用 $locations->orWhereRaw:

写的一样
select * from locations where 
country_name LIKE %united% OR state_name LIKE %united% OR city_name LIKE %united% 
AND 
country_name LIKE %atlanta% OR state_name LIKE %atlanta% OR city_name LIKE %atlanta%

我想要的是在逻辑上用 AND 将两个块分开,如下所示:

select * from locations where 
(country_name LIKE %united% OR state_name LIKE %united% OR city_name LIKE %united%)
AND 
(country_name LIKE %atlanta% OR state_name LIKE %atlanta% OR city_name LIKE %atlanta%)

显然,多次调用 whereRaw 并没有在逻辑上分隔每个查询。你必须手动完成。

这就是解决问题的方法。

$locations->whereRaw('(country_name LIKE ? OR state_name LIKE ? OR city_name LIKE ? )', ['%'.$word.'%','%'.$word.'%','%'.$word.'%']);

请注意 whereRaw 的第一个参数开头和结尾处的额外“(”和“)”字符。

试试这个:

$query = Location::query();

foreach($request->words as $word) {
   $query->where(function($qry) use ($word)  {
       $qry->where('country_name', 'like', '%'.$word.'%');
       $qry->orWhere('state_name', 'like', '%'.$word.'%');
       $qry->orWhere('city_name', 'like', '%'.$word.'%');
   });
}

$locations = $query->distinct()->paginate(10);