Laravel,each() 函数能做什么?

标签 laravel laravel-5 laravel-5.4

我没有具体的工作要做,只想知道 each() 能做什么。
我用谷歌搜索,看到了这篇文章:https://github.com/laravel/framework/issues/1380
它说

each is there to perform some operations on all items, that's all there is to it and that is what each is already doing.



有哪些操作?

最佳答案

each 方法将迭代集合中的项目,并允许您对每个项目执行代码。 each的区别和 map是不是同时each简单地遍历值,map用回调中返回的任何值替换该值。 each 的文档找到 here .如果你想看source code .

The each method iterates over the items in the collection and passes each item to a callback. If you would like to stop iterating through the items, you may return false from your callback.


$users->each(function($user, $key) {
     $user->update(['last_login' => Carbon::now()]);         
});

您要查询的“某些操作”是回调。在这种情况下,回调/操作是:
function($user, $key) {
    $user->update(['last_login' => Carbon::now()]);         
}

这会将集合上次登录的所有用户更新为当前时间。此外,如果您在 User 上有一个方法型号命名 updateLogin
class User extends Model
{
    public function updateLogin()
    {
        $this->update(['last_login' => Carbon::now()]);
    }
} 

实际上,您可以使用 $users 的集合执行以下操作:
$users->each->updateLogin();

您可以阅读有关此内容的信息 here :

Collections also provide support for "higher order messages", which are short-cuts for performing common actions on collections.

关于Laravel,each() 函数能做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44219929/

相关文章:

arrays - "Array to string conversion"错误 Laravel - 尝试将数组保存到数据库

php - 运行 "vendor"后丢失 "Composer Install"文件夹

php - Laravel DB::raw 使用 SELECT 列 AS "Example Name"

php - 多表中的 Laravel 关系

php - 传递给函数的 laravel 值不会传递到数据库中

laravel - 我的Docker镜像中不存在vendor文件夹

php - Laravel 检查记录是否存在

php - Laravel 5.3 中的 concat 集合

javascript - Laravel Uncaught ReferenceError webpackJsonp is not defined at app.js :1

php - 如何在 laravel 的链接按钮中隐藏 URL