如何在Laravel循环中替换查询条件?

How to replace query conditions in a loop in Laravel?

我有一个 user table 有姓名、状态和距离。我想让用户处于特定的 distance 下,如果结果为空,我想用递增的值再次检查它。

    $user = User::where('status',1);

    $i = 10;

    while($i < 50)
    {
        $user->having('distance', '<=', $i);

        if($user->get()->count())
            break;

        $i = $i+5;
    };

在第一个循环中,我正确地得到了 SELECT * from users where status = 1 and having distance <= 10 的查询。如果在第二个循环中结果为空,我得到的查询为 SELECT * from users where status = 1 and having distance <= 10 and having distance <= 15。我想将查询作为 SELECT * from users where status = 1 and having distance <= 15。我应该为此做些什么改变?

您正在处理对象,您应该使用 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;
}

另外您正在使用:

$query->get()->count()

是什么原因导致您从数据库中获取所有匹配查询的记录并计算它们的数量。如果你只需要他们的数量,最好只使用:

$query->count()