这是一个过于简化的示例,不适用于我。如何(使用这种方法,如果我实际上想要此特定结果,我知道有更好的方法)如何获得用户总数?
User::chunk(200, function($users)
{
return count($users);
});
这将返回NULL。知道如何从块函数获取返回值吗?
编辑:
这可能是一个更好的示例:
$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次,因此从它返回的闭包中返回任何内容都是没有意义的。
但是,您可以为闭包提供对方法范围的变量的访问,并允许闭包写入该值,这将使您间接返回结果。您可以使用use
关键字来执行此操作,并确保通过reference传入方法范围的变量,该变量是通过&
修饰符实现的。
例如,这将起作用;
$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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句