【问题标题】:Build an auto completion service with one or multiple search terms使用一个或多个搜索词构建自动完成服务
【发布时间】:2019-11-17 22:37:26
【问题描述】:

我正在为我的移动应用构建自动完成功能。结果需要来自我基于 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%)

【问题讨论】:

    标签: php laravel autocomplete


    【解决方案1】:

    试试这个:

    $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);
    

    【讨论】:

    【解决方案2】:

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

    这就是解决问题的方法。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-09
      • 1970-01-01
      • 2015-01-22
      • 1970-01-01
      • 1970-01-01
      • 2012-08-19
      • 2018-03-31
      • 1970-01-01
      相关资源
      最近更新 更多