gpt4 book ai didi

php - Laravel 全文搜索

转载 作者:可可西里 更新时间:2023-11-01 00:08:48 24 4
gpt4 key购买 nike

我正在尝试对数据库执行全文搜索查询。这是我的客户发给我的规范:

"The free text search limits the result of the data table to records with a matching first
name, last name, country, city, state, or zip code. If several words are input,
each word must match one of the columns for a record to be visible."

我在我的 Controller 中制作了一些非常丑陋的意大利面条代码来尝试它是否有效:

public function search($searchTerms){
$searchTerms = explode(' ', $searchTerms);
$results = array();
foreach ($searchTerms as $searchTerm) {
if (!People::where('firstname', 'LIKE', '%'.$searchTerm.'%')->get()->isEmpty()) {
array_push($results, People::where('firstname', 'LIKE', '%'.$searchTerm.'%')->get());
}
else if (!People::where('lastname', 'LIKE', '%'.$searchTerm.'%')->get()->isEmpty()) {
array_push($results, People::where('lastname', 'LIKE', '%'.$searchTerm.'%')->get());
}
}
return $results;
}

这是我对这个函数的调用:

$data->people = $this->search(Input::get('search'));

问题是如果没有搜索输入,我用它来获取所有数据:

$data->people = People::orderBy($order)->paginate(10);

通过将搜索结果作为数组获取,我在 View 中收到以下错误:

Undefined property: Illuminate\Database\Eloquent\Collection::$firstname (View: /home/projects/pplproject/app/views/index.blade.php) 

这应该如何以 Laravel 方式实现?

最佳答案

基本上,这里的目标应该是在一个查询中运行所有这些。开始了:

$searchTerms = explode(' ', $searchTerms);
$query = People::query();

foreach($searchTerms as $searchTerm){
$query->where(function($q) use ($searchTerm){
$q->where('firstname', 'like', '%'.$searchTerm.'%')
->orWhere('lastname', 'like', '%'.$searchTerm.'%')
->orWhere('country', 'like', '%'.$searchTerm.'%')
// and so on
});
}

$results = $query->get();

对于相关的模型你可以这样尝试:

foreach($searchTerms as $searchTerm){
$query->where(function($q) use ($searchTerm){
$q->where('firstname', 'like', '%'.$searchTerm.'%')
->orWhereHas('relationName', function($relation) use ($searchTerm){
$relation->where('relation_attribute', 'like', '%'.$searchTerm.'%');
});
});
}

关于php - Laravel 全文搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28486861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com