【发布时间】: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