2017-08-25 68 views
0

我有一个搜索查询在数据库中寻找书籍。它搜索标题和作者。通过多栏和相关排序的雄辩搜索

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

如何我可以优化它,以便显示标题为“魔山”和作者“托马斯·曼”第一项?

编辑:这是MySQL的版本:

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

+1

你为什么要使用一个循环,而不是只使用一个查询,您可以搜索标题为特定的作者?你为什么使用'LIKE'? – Noob

+0

循环:因为我将搜索字符串切成数组,例如:因为搜索不相同,例如在数据库中,它可能是“thomas mann”和搜索查询“mann” –

+0

但是,如果要优化if你不能改变LIKE子句。如果你总是得到更多的结果,这可能是结果。你能更具体地确定你想要的吗? – Noob

回答

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