Laravel全文搜索

时间:2015-02-12 20:11:40

标签: php database search laravel

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

"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."

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

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);

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

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

如何以 Laravel方式实现

1 个答案:

答案 0 :(得分:9)

基本上,这里的目标应该是在一个查询中运行这一切。这是:

$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.'%');
        });
    });
}