[英]If condition based query in laravel
我有一個查詢:
$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();
但是我想根據條件來查詢,這意味着如果類別是早餐,則僅顯示與早餐相關的食物;如果類別是午餐,則僅顯示與該類別相關的食物。我使用的是laravel 5.2
嘗試這樣的事情。 您不必一次全部查詢。 您可以通過幾個步驟將其組合。 在最后執行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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.