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());