2014-04-25 61 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

好点。谢谢你们! –