我没有具体的工作要做,只想知道 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/