【问题标题】:Codeigniter Server timeout - Running bulk DB queries inside for loopCodeigniter 服务器超时 - 在 for 循环中运行批量数据库查询
【发布时间】:2021-09-12 09:17:48
【问题描述】:

我在 foreach 循环中编写了一个数据库查询,在某些情况下,该查询使用不同的参数执行了 100 多次。

当 foreach 循环仅重复几轮时,脚本运行良好。

除了重新安排查询以在单个请求中获取所有数据之外,还有其他替代方法可以让我以有效的方式使用 foreach 循环运行脚本吗?

我当前的脚本

//  some where clauses here
$re = $this->db->get('cash_collection')->result();
    
$d=0;
foreach($re as $area){   // this loop runs 100+ rounds
    // call a function with single db query
    $re[$d]->area_paid = $this->Payment_m->get_inTotalForNormal($area->fka_id,$area->in_date);
    $d++;
}       
return $re;

【问题讨论】:

    标签: php mysql codeigniter activerecord foreach


    【解决方案1】:

    据我了解您的需求,我认为您需要将“result()”替换为“unbuffered_row()”。 result() 将立即将整个结果加载到内存中,而unbuffered_row() 方法返回单个结果行而不将整个结果预取到内存中。你可以了解更多here

    示例代码

    //  some where clauses here
    $re = $this->db->get('cash_collection');
        
    $d=0;
    while ($area = $query->unbuffered_row()) {   // this loop runs 100+ rounds
        // call a function with single db query
        $re[$d]->area_paid = $this->Payment_m->get_inTotalForNormal($area->fka_id,$area->in_date);
        $d++;
    }       
    return $re;
    

    现在您的脚本应该能够处理大型结果集了。

    注意 CI4getUnbufferedRow()

    【讨论】:

    • 感谢 mail2bapi 的回复。就我而言,您的解决方案不起作用。相反,我使用 get_compiled_select();将查询合并在一起的方法,它将时间从 78 秒缩短到 3 秒
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 2014-07-29
    相关资源
    最近更新 更多