2017-08-25 72 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();