2014-04-25 64 views
0

我試過各種方法來解決這個問題,但沒有爲我工作。Laravel選擇與多個在聲明

第一方法

$title = Character::find($selected_char->id)->title()->where('title', '=', 'Castle'); 
$title = $title->where('title', '=', 'City'); 
$title = $title->get(); 

第二方法

$title = Character::find($selected_char->id)->title()->where('title', '=', 'Castle')->where('title', '=', 'City')->get(); 

第三方法

$title = DB::select(DB::raw("select * from titles where titles.char_id = 5 and title = 'Castle' and title = 'City'")); 

的Ab的無ove方法工作。如果我只用一個where子句,它就可以完美地工作。例如:

$title = Character::find($selected_char->id)->title()->where('title', '=', 'City')->get(); 

$title = Character::find($selected_char->id)->title()->where('title', '=', 'Castle')->get(); 

我甚至試圖採取另一列比標題,但它不適用於第二個函數。我想從title表格中檢索標題爲City和Castle的行,並且在單個select語句中使用了多個where子句,並且它工作正常。不是現在。有什麼建議麼?提前致謝。

回答

3

你說:

我想中檢索從標題表中的行,其中標題爲城市和城堡

你可以試試這個:

$rowCOllection = DB::table('titles') 
        ->whereIn('title', array('City', 'Castle'))->get(); 

使用多個where

$rowCOllection = DB::table('titles') 
        ->where('title', 'City') 
        ->where('title', 'Castle')->get(); 

如果你想添加一個where子句titles.char_id,然後你可以用它喜歡:

$rowCOllection = DB::table('titles') 
        ->where('title', 'City') 
        ->where('title', 'Castle') 
        ->where('char_id', 5)->get(); 

您可能鏈儘可能多where,因爲你需要調用get()方法之前。您可以在whereIn之後加上where('char_id', 5),如whereIn(...)->where('char_id', 5),然後再撥get()

如果你有一個Title模型,那麼你可以這樣做使用同樣的事情:

Title::where(...)->where(...)->get(); 

一樣使用DB,只能更換DB::table('titles')Title,例如:

$rowCOllection = Title::where('title', 'City') 
    ->where('title', 'Castle') 
    ->where('char_id', 5)->get(); 

什麼Character在這裏?

+1

$ title = Character :: find($ selected_char-> id) - > title() - > whereIn('title',array('City','Castle')) - > get();爲我工作。謝謝您的回答。我不知道where子句的這種格式。這對未來肯定會有幫助。 –

+0

不客氣,很高興幫助:-) –

1

我真的不知道如何在PHP中工作,你的雙->where(,但在SQL這裏是錯誤:

當你說where title = 'a' and title = 'b',這就像你說:好給我的東西,其中0 = 1 它什麼都不返回

你可以這樣做:

select * from titles where titles.char_id = 5 and (title = 'Castle' or title = 'City') 

獲取所有數據,其中標題等於城堡或城市

或者

select * from titles where titles.char_id = 5 and title IN ('Castle','City') 

獲取所有數據,其中標題中使用中值爲城堡或城市

我敢肯定你會找到一種方法來在PHP中做到這一點。

+0

我確實在第一個答案中找到了我的評論中描述的方法。感謝您的指示。 –

+0

@Serban' - > whereIn'這正是SQL中的'IN'運算符,並且我在他之前回答的方式...希望你理解爲什麼這不能在sql邏輯中工作。 – Ryx5

0

假設你正在使用Laravel 4

而且性格是你的模型從雄辯

擴展不混合查找和WHERE。

查找是針對單用途找到與事後排序(所以order by和等)

所以,如果你想環比上漲查詢

Character::where()->where()->where()-get() (don't forget the get or else you wont get a result)

這樣你尊重雄辯的功能。

請注意您的第一個方法->title()有缺陷,因爲您調用了您在模型中自定義創建的函數 - 這就是爲什麼它不起作用。

注意:如果你不想使用雄辯,WereWolf Alpha的方法也可以工作,因爲他提供的代碼可以工作,但這就是流利的符號...所以請選擇。

+0

好點。謝謝你們! –