Php 使用laravel中的长度感知分页器搜索结果分页太慢

Php 使用laravel中的长度感知分页器搜索结果分页太慢,php,laravel,search,pagination,Php,Laravel,Search,Pagination,我正在尝试在我的应用程序中实现最相关的搜索 我有一个搜索页面,用搜索输入字段搜索客户。输入字段与数据库中的某些字段匹配。我有以下数据库结构 客户 电子邮件,状态 字段 名称、slug、状态 字段值(字段表包含姓名、地址、电话号码等字段) 客户id、字段id、值 我只需从搜索页面获取输入值,并将字段值表中的值与如下字段匹配: 全名、名称、地址等 对于每个匹配,我都增加了一个权重参数,稍后我将按权重排序。这是代码 搜索键数组: $keyword = $request->get('keyword

我正在尝试在我的应用程序中实现最相关的搜索

我有一个搜索页面,用搜索输入字段搜索客户。输入字段与数据库中的某些字段匹配。我有以下数据库结构

客户

电子邮件,状态

字段

名称、slug、状态

字段值(字段表包含姓名、地址、电话号码等字段)

客户id、字段id、值

我只需从搜索页面获取输入值,并将字段值表中的值与如下字段匹配:

全名、名称、地址等

对于每个匹配,我都增加了一个权重参数,稍后我将按权重排序。这是代码

搜索键数组:

$keyword = $request->get('keyword');

/**
* Split key into string array
*/
$keys = explode(' ', $keyword);

$searchItems = [];
foreach ($keys as $key){
    $key = str_replace(' ','', $key);
    $key = preg_replace('/[^a-zA-Z0-9_]/', '', $key);
    if($key){
        $searchItems[] = $key;
    }
}
$keys = $searchItems;
搜索逻辑

/**
 * Filter customer Ids based on search keys and field ids
 *
 * @param $fieldIds
 * @param $customerIds
 * @param $keys
 * @return mixed
 */
public function searchCustomersForYellowPage($fieldIds, $customerIds, $keys)
{
    $result =  $this->model->whereIn('customer_id', $customerIds)
                        ->whereIn('field_id', $fieldIds)
                        ->where(function ($query) use ($keys){
                            foreach ($keys as $key){
                                $query->orWhere('value', 'LIKE', '%'.$key.'%');
                            }
                        })
                        ->groupBy('customer_id')
                        ->pluck('customer_id');

    return $result->sortByDesc(function ($item) use($fieldIds, $keys){
                $weight = 0;
                foreach ($fieldIds as $fieldId){
                    foreach ($keys as $key){
                        $exists = $this->model->where('field_id', $fieldId)
                                            ->where('customer_id', $item)
                                            ->where('value', 'LIKE', '%'.$key.'%')
                                            ->exists();
                        if($exists)
                            $weight++;
                    }
                }
                return $weight;

    })->toArray();
}
在该函数中,
$keys
参数与上面解释的相同,
$customerID
是所有客户的id,
$fieldID
是用于搜索的字段的id

此函数按最相关的顺序返回搜索后所有客户ID的数组。后来,我使用此数组获取所有客户,并使用自定义长度感知分页器进行分页


我面临的问题是,它需要很长时间,在分页之后,当我加载每个页面时,它需要同样长的时间。有没有办法只执行这段代码一次,并在多个页面上对搜索结果进行分页,这样第一种情况需要很长时间,而第二种情况下加载第三种情况则需要更快的时间。。。。页面。

在您对
SearchCustomers ForYellowPage
的第一次查询中,您已经使用了该组,因此请使用
选择(['customer\u id',DB::raw('count(*)as cnt'))
和最后一次
orderBy('cnt','desc'))

您用于权重的代码可能性能较低,因为对于每10个结果,如果3是您的键,它将由10*10*3执行,因此总共执行300次查询。第二个十次我假设fields@DhavalPurohit我有四个字段,键的长度可以是3/4,那么最好的方法是什么呢?为什么不使用e使用客户id进行分组计数以查找权重?在您第一次查询
searchCustomersForYellowPage
时,您已经使用了该分组,因此请使用
选择(['customer\u id',DB::raw('count(*)as cnt'))
和最后一次
orderBy('cnt','desc'))
再次感谢大家的欢迎这就是
的意思。互相帮助。