Laravel 全文搜索
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28486861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel full text search
提问by Peter
I'm trying to implement a full text search query to the database. This is in the specification that my client sent me:
我正在尝试对数据库实施全文搜索查询。这是我的客户发给我的规范:
"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."
I made some veryugly spaghetti code in my controller to try if it works:
我在我的控制器中做了一些非常难看的意大利面代码来尝试它是否有效:
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;
}
And this is my call to this function:
这是我对这个函数的调用:
$data->people = $this->search(Input::get('search'));
The problem is that if there is no search input, I use this to get all data:
问题是,如果没有搜索输入,我用它来获取所有数据:
$data->people = People::orderBy($order)->paginate(10);
And by getting the search results as an array, I get the following error in my views:
通过将搜索结果作为数组获取,我的视图中出现以下错误:
Undefined property: Illuminate\Database\Eloquent\Collection::$firstname (View: /home/projects/pplproject/app/views/index.blade.php)
How should this be implemented in the Laravel way?
这应该如何以Laravel 方式实现?
回答by lukasgeiter
Basically, the goal here should be to run this all in one query. Here goes:
基本上,这里的目标应该是在一个查询中运行所有这些。开始:
$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();
For related models you can try something like this:
对于相关模型,您可以尝试以下操作:
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.'%');
});
});
}