Laravel块返回null [英] Laravel chunk returns null

查看:91
本文介绍了Laravel块返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对查询进行分块,因为这会使PHP的内存不足,但是下面的代码只会转储null:

I'm needing to chunk my query as it's making PHP run out of memory, however the below code just dumps null:

$chunked = $query->chunk(25, function ($events) {
    //dd($events);
});
dd($chunked);

但是,当我执行以下操作时,它会转储25的第一个块:

However, when I do the below, it dumps the first chunk of 25:

$chunked = $query->chunk(25, function ($events) {
    dd($events);
});
//dd($chunked);

dd($events);更改为return $eventsreturn true之类,遍历每个块中的每个项目并将其返回的任何组合都无法工作.

No combination of changing dd($events); to the likes of return $events, return true, iterating over each item in each chunk and returning that - works.

我是愚蠢/做错了还是不是应该正常工作?

Am I stupid/doing something wrong or is this not working like it should?

推荐答案

chunk()是一种辅助方法,可用于Query Builder或Eloquent Builder的实例.在这两种情况下,该方法均返回void:

chunk() is a helper method which you can use on an instance of Query Builder or Eloquent Builder. In both cases, the method returns void:

  • Query Builder
  • Eloquent Builder

这意味着您的$chunked变量将始终为空.

This means that your $chunked variable will be always empty.

您需要使用以下语法:

查询生成器

DB::table('users')->chunk(100, function($users) {
    foreach ($users as $user) {
        //
    }
});

口才

Flight::chunk(200, function ($flights) {
    foreach ($flights as $flight) {
        //
    }
});

基本上,您要做的就是在chunk()的回调函数中使用循环来修改结果.

Basically, all you need to do is to use a loop within the callback function of chunk() to modify your results.

这篇关于Laravel块返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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