2014-01-14 70 views
3

我正在Laravel 4.1中構建一個類似於Facebook的AJAX搜索功能。搜索字段應搜索users表,對照first_name,last_nameemailLaravel raw FULLTEXT查詢類似於Facebook搜索

我可能輸入的任何術語的如以下術語或部分:

首先我想:

User::where('email', 'LIKE', $search) 
    ->orWhere('first_name', 'LIKE', $search) 
    ->orWhere('last_name', 'LIKE', $search) 
    ->get(); 

但是,只關心一個關鍵詞匹配。然後我試圖通過空間爆炸輸入和建立這樣的查詢:

User::whereRaw("MATCH (first_name, last_name, email) 
       AGAINST ('$explode[0]' IN BOOLEAN MODE) 
       AND MATCH (first_name, last_name, email) 
       AGAINST ('$explode[1]' IN BOOLEAN MODE)") 
    ->get(); 

其作品,但只得到精確匹配(「賈裏德」,「eitnier」或「賈裏德eitnier」)

我需要更改什麼才能獲得LIKE比賽,但輸入的術語組合是?

回答

5

我能夠在this post的幫助下解決這個問題。以下是最終代碼:

$input = Input::get('input'); 

$exp = explode(' ', $input); 

$s = ''; 
$c = 1; 
foreach ($exp AS $e) 
{ 
    $s .= "+$e*"; 

    if ($c + 1 == count($exp)) 
     $s .= ' '; 

    $c++; 
} 

$query = "MATCH (first_name, last_name, email) AGAINST ('$s' IN BOOLEAN MODE)"; 
// $query looks like 
// MATCH (first_name, last_name, email) AGAINST ('+jar* +eitni*' IN BOOLEAN MODE) 

$users = User::whereRaw($query)->get();