如果在laravel中基于条件的查询

时间:2016-07-21 06:13:36

标签: php laravel-5 phpmyadmin laravel-5.2

我的查询为:

 $Category = DB::table('food')
    ->select('food.Food_id','food.FoodName','categories.CategoryName')
    ->join('categories','categories.Category_id','=','food.Category_id')
    ->where('categories.CategoryName', '=','Breakfast')
    ->get();

但是我想根据if条件进行查询,这意味着如果Category是Breakfast,那么只显示与Breakfast相关的食品或IF Category是Lunch,那么只显示与该类相关的食品。我正在使用{{1} }

1 个答案:

答案 0 :(得分:0)

尝试这样的事情。您不必一次进行查询。您可以通过几个步骤将其组合起来。在您最终执行get()find()或类似内容之前,它不会返回查询结果,而只会返回查询构建器对象,如果我没有错的话。

// You should probably send this as a method parameter so you can determine if you should get one, or the other category
$cat = 1;

$Category = DB::table('food')
    ->select('food.Food_id','food.FoodName','categories.CategoryName')
    ->join('categories','categories.Category_id','=','food.Category_id');
if($cat == 0){
    $Category = $Category->where('categories.CategoryName', '=','Breakfast');    
}
if($cat == 1){
    $Category = $Category->where('categories.CategoryName', '=','Lunch');
}
$Category = $Category->get();