如何获取 Laravel 块的返回值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26026795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:09:45  来源:igfitidea点击:

How can I get the return value of a Laravel chunk?

phplaravel

提问by Citizen

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);
});

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

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

Edit:

编辑:

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

回答by RJ Lohan

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 chunkpotentially invokes this anonymous function N times, it makes no sense for it to return anything back from the closures it invokes.

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

Howeveryou 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 usekeyword, and make sure to pass the method-scoped variable in by reference, which is achieved with the &modifier.

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

This will work for example;

例如,这将起作用;

$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

回答by Elizabeth Chikoka

$regions = array();

Regions::chunk(10, function($users) use (&$regions ) {

    $stickers = array();

    foreach ($users as $user)
    {
        $user->sababu = ($user->region_id > 1)? $user->region_id : 0 ;
        $regions[] = $user;
    }

});

echo json_encode($regions);