2017-02-14 14 views
0

案例關係查詢orWhere覆蓋其他何在

調查基礎上返回x量成果的基礎上公寓的幾個問題。

公寓可以有靜態市盈率(price),或價格區間(price_minprice_max) - 並非所有的公寓有一個靜態的價格又那麼他們由價格區間定義(例如900-1000月租)

問題

沒有orWhere([['price_min', '!=', null], ['price_max', '!=', null], ['price_min', '<', '900']]一切工作正常。只有經過where條件的公寓才被退回;雖然當被添加all apartments with a price rangeorWhere條件(所以沒有price)返回的,不管前面的條件,如floorsun

代碼

$selectedType = Type::where('slug', '=', $slug)->where('type', '=', 'studio')->with(['apartments' => function ($query) use ($request) { 
    $query->where('status', '!=', 'sold'); 

    if ($request->floor == 'low') { 
     $query->where('floor', '<', '5'); 
    } elseif ($request->floor == 'mid') { 
     $query->where('floor', '>', '1')->where('floor', '<', '6'); 
    } elseif ($request->floor == 'high') { 
     $query->where('floor', '>', '4'); 
    } 

    if ($request->sun == 'morning_sun') { 
     $query->where('sun', '=', 'morning'); 
    } elseif ($request->sun == 'evening_sun') { 
     $query->where('sun', '=', 'evening'); 
    } 

    if ($request->price == '1') { 
     $query->where('price', '<', '900')->orWhere([['price_min', '!=', null], ['price_max', '!=', null], ['price_min', '<', '900']]); 
    } elseif ($request->price == '2') { 
     $query->where('price', '<', '999')->orWhere([['price_min', '!=', null], ['price_max', '!=', null], ['price_min', '<', '999']]); 
    } 
}])->first(); 
+0

個人(因爲我不知道laravel),我會覺得更容易考慮MySQL的隔離,然後把它留給你該查詢轉換成laravel – Strawberry

+0

什麼數據類型是'price_min'?確保一個空字符串不是null,所以也許應該是''price_min','!=',「」'。 – Markinson

回答

1

您需要組或在的條件下。下面應該做的伎倆:

if ($request->price == '1') { 
    $query->where(function($q) { 
     $q->where('price', '<', '900')->orWhere([['price_min', '!=', null], ['price_max', '!=', null], ['price_min', '<', '900']]); 
    }); 
} elseif ($request->price == '2') { 
    $query->where(function($q) { 
     $q->where('price', '<', '999')->orWhere([['price_min', '!=', null], ['price_max', '!=', null], ['price_min', '<', '999']]); 
    }); 
}