Laravel全文搜索

编程入门 行业动态 更新时间:2024-10-25 14:26:52
本文介绍了Laravel全文搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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 very ugly 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)

该如何以 Laravel方式实现?

推荐答案

基本上,这里的目标应该是在一个查询中全部运行.去吧:

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

更多推荐

Laravel全文搜索

本文发布于:2023-10-18 23:50:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1505784.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:全文   Laravel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!