Laravel 5中all()和toArray()之间的区别

编程入门 行业动态 更新时间:2024-10-27 06:28:14
本文介绍了Laravel 5中all()和toArray()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当我管理需要转换为数组的集合时,通常使用toArray().但是我也可以使用all().我不知道这两个功能的区别...

When I manage a collection that I need to convert to an array, I usually use toArray(). But I can also use all(). I'm not aware of the diference of those 2 function...

有人知道吗?

推荐答案

如果它是Eloquent模型的集合,那么这些模型也将通过 toArray()

If it's a collection of Eloquent models, the models will also be converted to arrays with toArray()

$col->toArray();

所有这些都将返回一个Eloquent模型数组,而不将其转换为数组.

With all it will return an array of Eloquent models without converting them to arrays.

$col->all();

toArray方法将集合转换为纯PHP数组.如果集合的值是Eloquent模型,则这些模型也将转换为数组: toArray()

The toArray method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays: toArray()

all()返回集合中的项目

/** * Get all of the items in the collection. * * @return array */ public function all() { return $this->items; }

toArray()返回集合的项目,并将它们转换为可数组的数组:

toArray() returns the items of the collection and converts them to arrays if Arrayable:

/** * Get the collection of items as a plain array. * * @return array */ public function toArray() { return array_map(function ($value) { return $value instanceof Arrayable ? $value->toArray() : $value; }, $this->items); }

例如:像这样从数据库中获取所有用户:

For example: Grab all your users from database like this:

$users = User::all();

然后以各种方式丢弃它们,您将看到区别:

Then dump them each way and you will see difference:

dd($users->all());

并使用toArray()

And with toArray()

dd($users->toArray());

更多推荐

Laravel 5中all()和toArray()之间的区别

本文发布于:2023-11-23 19:30:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622617.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区别   Laravel   toArray

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!