【问题标题】:How to replace query conditions in a loop in Laravel?如何在 Laravel 的循环中替换查询条件?
【发布时间】:2018-09-04 04:28:18
【问题描述】:

我有一个user 表,其中包含名称、状态和距离。我想获取特定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 &lt;= 10。如果在第二个循环中结果为空,我将查询为SELECT * from users where status = 1 and having distance &lt;= 10 and having distance &lt;= 15。我想得到SELECT * from users where status = 1 and having distance &lt;= 15的查询。我应该为此做些什么改变?

【问题讨论】:

    标签: sql laravel laravel-5 eloquent laravel-5.6


    【解决方案1】:

    你正在这里处理对象,你应该使用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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-21
      • 2020-10-01
      • 2013-11-11
      • 1970-01-01
      • 2020-07-09
      • 2013-07-13
      • 2018-11-04
      • 2012-12-13
      相关资源
      最近更新 更多