Laravel 5中all()和toArray()之间的区别 [英] Difference between all() and toArray() in Laravel 5

查看:1011
本文介绍了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()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆