How to chunk results from a custom query in Laravel

前端 未结 8 1345
北海茫月
北海茫月 2020-12-17 18:37

I have a custom query that grabs data from the old system and maps it to models in the new system. The query looks like this:

$companies = DB::connection(\'leg

8条回答
  •  一向
    一向 (楼主)
    2020-12-17 19:19

    None of these answers worked for me. I created my own function based on @deyes answer.

    private static function chunk($query, $max, $function) {
        $counter = preg_replace('/SELECT (.*?) FROM/', 'SELECT COUNT(*) FROM', $query);
        $total = DB::connection('legacy')->select($counter)[0];
        $total = (array)$total;
        $total = $total['COUNT(*)'];
    
        $pages = ceil($total / $max);
    
        for ($i = 1; $i < ($pages + 1); $i++) {
            $offset = (($i - 1)  * $max);
            $start = ($offset == 0 ? 0 : ($offset + 1));
            $items = DB::connection('legacy')->select($query . ' LIMIT ' . $offset . ', ' . $max);
    
            $function($items);
    
            unset($items);
        }
    }
    

    Usage

    YourClass::chunk('SELECT * FROM tablename', 50, function($items) {
        //Work with $items.
    });
    

    Please note that this a simple quick fix and your query probably has to be fairly simple as I'm using search-replace to build a count query and I'm just tacking on LIMIT X, Y to the end of the query but it works for me.

提交回复
热议问题