gpt4 book ai didi

php - 如何获取 Laravel block 的返回值?

转载 作者:行者123 更新时间:2023-12-03 00:43:25 25 4
gpt4 key购买 nike

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

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

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

编辑:

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

$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 关键字执行此操作,并确保通过引用传递方法范围的变量,这是通过 & 修饰符实现的.

这将起作用;

$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

关于php - 如何获取 Laravel block 的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26026795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com