雄辩地搜索许多列和相关排序

时间:2017-08-25 11:02:46

标签: mysql laravel orm eloquent

我有一个搜索查询,在数据库中查找图书。它搜索标题和作者。

$searchQuery = explode(" ", $searchString);
$results = $this
                ->where(function ($query) use($searchQuery) {
                    for ($i = 0; $i < count($searchQuery); $i++){
                        $query->orwhere('title', 'LIKE',  '%' . $searchQuery[$i] .'%');
                    }
                })
                ->orWhereHas('authors', function ($query) use ($searchQuery)  {
                    for ($i = 0; $i < count($searchQuery); $i++){
                        $query->orwhere('author', 'LIKE', '%' . $searchQuery[$i] .'%');
                    }
                })
                ->get();

我如何优化它,以便显示带有标题的条目&#34; 魔术山&#34;和作者&#34; Thomas Mann &#34;第一λ

编辑:这是mysql版本:

&#13;
&#13;
select * from `books_catalogue` where (`title` LIKE '%magic%' or `title` LIKE '%mountain%' or `title` LIKE '%thomas%' or `title` LIKE '%mann%') or exists (select * from `authors` inner join `author_books_catalogue` on `authors`.`id` = `author_books_catalogue`.`author_id` where `author_books_catalogue`.`books_catalogue_id` = `books_catalogue`.`id` and (`author` LIKE '%magic%' or `author` LIKE '%mountain%' or `author` LIKE '%thomas%' or `author` LIKE '%mann')) or (`query` LIKE '%magic%' or `query` LIKE '%mountain%' or `query` LIKE '%thomas%' or `query` LIKE '%mann%');
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

我最终添加了一个包含varchar中的标题和作者的FULLTEXT字段。这样我就可以使用Mysql匹配功能。这工作流畅而快速。

现在代码如下:

 $results = $this
                ->whereRaw("MATCH (search_summary) AGAINST ('".$searchString."')  ORDER BY MATCH(search_summary) AGAINST('".$searchString."') ASC, books_catalogue.priority DESC;")
                ->get();