Reputation: 1587
I have a user
table with name, status and distance. I want to get the users under a particular distance
and if the result is empty I want to check it again with an incremented value.
$user = User::where('status',1);
$i = 10;
while($i < 50)
{
$user->having('distance', '<=', $i);
if($user->get()->count())
break;
$i = $i+5;
};
In the first loop I got the query correctly as SELECT * from users where status = 1 and having distance <= 10
. If the result is empty in the second loop I got the query as SELECT * from users where status = 1 and having distance <= 10 and having distance <= 15
. I want to get the query as SELECT * from users where status = 1 and having distance <= 15
. What change should I do for this?
Upvotes: 0
Views: 203
Reputation: 111859
You are working here on objects and you should use clone
:
$user = User::where('status',1);
$i = 10;
while($i < 50)
{
$query = (clone $user)->having('distance', '<=', $i);
if($query->get()->count())
break;
$i = $i+5;
}
In addition you are using:
$query->get()->count()
what causes that you get all records matching query from database and calculate their amount. If you just need to have their count, it's much better to use just:
$query->count()
Upvotes: 1