优化填充可搜索文本字段的 Laravel 代码

问题描述 投票:0回答:1

我有以下运行良好的代码,我尝试使用 Laravel 在可搜索文本字段中获取大约 50,000 个城市,但这需要大量时间并且浏览器变得不活动。我怎样才能优化以使其更快。

public function searchCity()
{
    $country = Country::with('states.cities')->find(231);

    if ($country) {
        $cities = $country->states->flatMap->cities->pluck('name')->toArray();;
        return $cities;
    } else {
        return response()->json(['message' => 'Country not found'], 404);
    }

}

和ajax

 $.ajax({
        method: "GET",
        url: "/searchcity",
        success: function (response) {
          townsTags = response;
          startAutocomplete(townsTags, "#search_towns");
        }
      });
ajax laravel laravel-livewire
1个回答
0
投票

为什么不在服务器端执行搜索?

您可以将您正在搜索的项目作为查询参数发送:

$.ajax({
    method: "GET",
    url: "/searchcity",
    data: { query: search },
    success: function (response) {
        townsTags = response;
        startAutocomplete(townsTags, "#search_towns");
    }
});

然后搜索具体结果:

public function searchCity(Request $request)
{
    $country = Country::with('states.cities')->find(231);

    $query = $request->input('query');

    if ($country) {
        $cities = $country->states
            ->flatMap->cities
            ->pluck('name')
            ->where('name', 'like', '%' . $query . '%')
            ->toArray();

        return $cities;
    } else {
        return response()->json(['message' => 'Country not found'], 404);
    }
}

还可以考虑对结果实施延迟加载。显示一些初始结果并在用户向下滚动时加载更多结果。

© www.soinside.com 2019 - 2024. All rights reserved.