如何获得Laravel块的返回值?

Cit*_*zen 12 php laravel

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

User::chunk(200, function($users)
{
   return count($users);
});
Run Code Online (Sandbox Code Playgroud)

这返回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
Run Code Online (Sandbox Code Playgroud)

RJ *_*han 26

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

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

这将起作用;

$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
Run Code Online (Sandbox Code Playgroud)

  • 对于那些发现这对他们不起作用的人,对我来说,计数会重置每个块循环。我忘了将 `&` 参数添加到 `use` 语句中。如果您添加它,它将正常工作。 (2认同)