2013-03-01 65 views
1

我想用雄辯來搜索兩個可選表:Laravel雄辯搜索兩個可選字段

$users = User::where('ProfileType', '=', 2) 
       ->where(function($query) { 
        $query->where('BandName', 'LIKE', "%$artist%"); 
        $query->or_where('Genre', 'LIKE', "%$genre%"); 
       })->get(); 

這工作正常的回報,當用戶執行一個空搜索所有結果,但我不知道如何調整它以便在存在時搜索樂隊名稱,反之亦然。

+0

所以將查詢永遠是:WHERE ProfileType = 2 AND(BandName = '富' 或流派= '吧')?我試圖找出哪些搜索值總是存在,哪些可能並不總是存在。 – 2013-03-04 17:05:55

+0

是的,ProfileType將始終存在,但BandName和Genre都是可選的,甚至可以留空。謝謝 – tmartin314 2013-03-05 20:59:04

回答

2

建立在這裏維尼的答案是什麼工作:

// Instantiates a Query object 
$query = User::where('ProfileType', '=', '2'); 

// Adds a clause to the query 
if ($artist = Input::get('artist')) { 
    $query->where('BandName', 'LIKE', "%$artist%"); 
    // Temp Usernamesearch 
    $query->or_where('NickName', 'LIKE', "%$artist%"); 
} 

// Genre - switch function if artist is not empty 
if ($genre = Input::get('genre')) { 
    $func = ($artist) ? 'or_where' : 'where'; 
    $query->$func('Genre', 'LIKE', "%$genre%"); 
} 

// Executes the query and fetches it's results 
$users = $query->get(); 

原來,第二可選字段必須使用or_where只有$藝術家沒有設置。

感謝您的幫助

0

我認爲這是你以後的事情。你的觀點將會有一種搜索藝術家/流派的形式,其中一種或另一種可以被設置,或者兩種都可以,或者沒有。

$users = User::where('ProfileType', '=', 2); 

if (Input::has('artist')) { 
    $users = $users->where('BandName', 'LIKE', '%'.Input::get('artist').'%'); 
} 

if (Input::has('genre')) { 
    $users = $users->where('Genre', 'LIKE', '%'.Input::get('genre').'%'); 
} 

$users = $users->get(); 
8

只是爲了解釋下面的答案會發生什麼:

洋洋灑灑做了一件棘手的事情在這裏:當你打電話User::where(...)它返回一個Database\ Query對象。這與構建SQL查詢的可鏈接對象DB::table('users')->where(...)基本相同。

因此,有:

// Instantiates a Query object 
$query = User::where('ProfileType', '=', '2'); 
$query->where(function($query) { 
    // Adds a clause to the query 
    if ($artist = Input::get('artist')) { 
     $query->where_nested('BandName', 'LIKE', "%$artist%", 'OR'); 
    } 
    // And another 
    if ($genre = Input::get('genre')) { 
     $query->where_nested('Genre', 'LIKE', "%$genre%", 'OR'); 
    } 
}); 

// Executes the query and fetches it's results 
$users = $query->get(); 
+0

這個答案看起來不錯,但由於某種原因沒有找到任何結果。不知道是什麼問題 – tmartin314 2013-03-06 19:58:38

+0

噢,我沒有意識到你想用OR搜索多個字段。通常每個字段的行爲都像一個過濾器。在這種情況下,AND就是要走的路。我將編輯答案並提供一些說明。 – vFragosop 2013-03-06 20:34:20

+0

這可以在一個輸入字段中完成嗎?例如一個名稱篩選器,用於檢查篩選器是否等於名字或姓氏... – nclsvh 2016-01-18 14:33:19