php - Relationship query orWhere overwrites other wheres -
case
survey based on few questions returns x
amount of apartments based on results.
an apartment can have static price (price
), or price range (price_min
, price_max
) - not apartments have static price yet being defined price range (for example 900-1000 monthly rent)
problem
without orwhere([['price_min', '!=', null], ['price_max', '!=', null], ['price_min', '<', '900']]
works fine. apartments past where
conditions being returned; although when orwhere
condition being added all apartments price range
(so no price
) being returned, no matter previous conditions such floor
or sun
code
$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();
you need group orwhere conditions. following should trick:
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']]); }); }
Comments
Post a Comment