如何从Laravel中的自定义查询中块结果 [英] How to chunk results from a custom query in Laravel

查看:217
本文介绍了如何从Laravel中的自定义查询中块结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义查询,可以从旧系统中获取数据,并将其映射到新系统中的模型。查询如下所示:



$ companies = DB :: connection('legacy') - > select(...) ;因为它是很多数据,我想使用Eloquent的大块功能(只是从他们的文档中复制的示例代码):



  User :: chunk(200,function($ users)
{
foreach($ users as $ user)
{
//
}
});

如何实现?






编辑:我的代码现在看起来像这样,这样做没有反应:

  DB :: connection('legacy') - > select(SELECT * FROM companies) - > chunk(200,function($ companies){
foreach($ companies as $ company){
// dd($ company);
$ entity = Entity :: firstOrNew(['external_id'=> $ company-> companyKey]);
$ entity-> name = $ company - > companyName;
$ entity-> save();
}
});


解决方案

尝试这样:

 <?php 

$ max = 100;
$ total = DB :: connection('legacy') - > select(...) - > count();
$ pages = ceil($ total / $ max); ($ i = 1; $ i<($ pages + 1); $ i ++){
$ offset =(($ i - 1)* $ max)
$ start =($ offset == 0?0:($ offset + 1));
$ legacy = DB :: connection('legacy') - > select(...) - > skip($ start) - > take($ max) - > get();
/ *做东西* /
}

基本上复制了Laravel的Paginator没有额外的开销。 >

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('legacy')->select("...");

And since it's a lot of data, I'd like to use Eloquent's chunk feature (just sample code copied from their docs):

User::chunk(200, function($users)
{
    foreach ($users as $user)
    {
        //
    }
});

How do I implement this?


Edit: My code now looks like this, which results in no response:

DB::connection('legacy')->select("SELECT * FROM companies")->chunk(200, function($companies) {
    foreach ($companies as $company) {
        // dd($company);
        $entity       = Entity::firstOrNew(['external_id' => $company->companyKey]);
        $entity->name = $company->companyName;
        $entity->save();
    }
});

解决方案

Try something like this:

<?php

$max = 100;
$total = DB::connection('legacy')->select("...")->count();
$pages = ceil($total / $max);
for ($i = 1; $i < ($pages + 1); $i++) {
    $offset = (($i - 1)  * $max);
    $start = ($offset == 0 ? 0 : ($offset + 1));
    $legacy = DB::connection('legacy')->select("...")->skip($start)->take($max)->get();
    /* Do stuff. */
}

Basically duplicates what Laravel's Paginator does without the extra overhead.

这篇关于如何从Laravel中的自定义查询中块结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆