如何获取Laravel块的返回值? [英] How can I get the return value of a Laravel chunk?

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

问题描述

这是一个过于简化的示例,对我不起作用.如何(使用这种方法,如果我确实想要这个特定的结果,我知道有更好的方法)如何获得用户总数?

Here's an over-simplified example that doesn't work for me. How (using this method, I know there are better ways if I were actually wanting this specific result), can I get the total number of users?

User::chunk(200, function($users)
{
   return count($users);
});

这将返回NULL.知道如何从块函数中获取返回值吗?

This returns NULL. Any idea how I can get a return value from the chunk function?

这可能是一个更好的例子:

Here might be a better example:

$processed_users = DB::table('users')->chunk(200, function($users)
{
   // Do something with this batch of users. Now I'd like to keep track of how many I processed. Perhaps this is a background command that runs on a scheduled task.
   $processed_users = count($users);
   return $processed_users;
});
echo $processed_users; // returns null

推荐答案

我认为您无法以这种方式实现想要的目标.匿名函数是由chunk方法调用的,因此您从闭包中返回的所有内容都会被chunk吞噬.由于chunk可能会调用N次此匿名函数,因此从它调用的闭包中返回任何内容都是没有意义的.

I don't think you can achieve what you want in this way. The anonymous function is invoked by the chunk method, so anything you return from your closure is being swallowed by chunk. Since chunk potentially invokes this anonymous function N times, it makes no sense for it to return anything back from the closures it invokes.

但是您可以为闭包提供对方法范围变量的访问,并允许闭包写入该值,这将使您间接返回结果.您可以使用use关键字执行此操作,并确保在中按引用传递方法范围的变量,该变量是通过&修饰符实现的.

However you can provide access to a method-scoped variable to the closure, and allow the closure to write to that value, which will let you indirectly return results. You do this with the use keyword, and make sure to pass the method-scoped variable in by reference, which is achieved with the & modifier.

例如,这将起作用;

$count = 0;
DB::table('users')->chunk(200, function($users) use (&$count)
{
    Log::debug(count($users)); // will log the current iterations count
    $count = $count + count($users); // will write the total count to our method var
});
Log::debug($count); // will log the total count of records

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

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