当我管理需要转换为数组的集合时,我通常使用toArray()
。但我也可以使用all()
。我不知道这两个功能的区别...
有人知道吗?
如果它是 Eloquent 模型的集合,模型也会被转换为数组toArray()
$col->toArray();
总之,它将返回 Eloquent 模型的数组,而不将它们转换为数组。
$col->all();
toArray 方法将集合转换为普通的 PHP 数组。如果集合的值是 Eloquent 模型,则模型也会转换为数组:toArray() https://laravel.com/docs/5.4/collections#method-toarray
all()返回集合中的项目
/**
* Get all of the items in the collection.
*
* @return array
*/
public function all()
{
return $this->items;
}
toArray()返回集合的项目并将它们转换为数组(如果 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);
}
例如:从数据库中获取所有用户,如下所示:
$users = User::all();
然后以各种方式转储它们,您会看到差异:
dd($users->all());
并使用 toArray()
dd($users->toArray());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)