【问题标题】:Difference between all() and toArray() in Laravel 5Laravel 5 中 all() 和 toArray() 的区别
【发布时间】:2017-09-03 09:30:30
【问题描述】:

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

有人知道吗?

【问题讨论】:

  • all() 将返回Eloquent Objects,而toArray() 将返回关联数组

标签: arrays laravel collections


【解决方案1】:

如果是 Eloquent 模型的集合,模型也会通过 toArray()

转换为数组
    $col->toArray();

它会返回一个 Eloquent 模型数组,而不会将它们转换为数组。

    $col->all();

toArray 方法将集合转换为普通的 PHP 数组。如果集合的值是 Eloquent 模型,模型也会被转换为数组: 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());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 2017-11-13
    • 2016-09-05
    • 1970-01-01
    • 2017-09-07
    • 2015-08-05
    • 1970-01-01
    相关资源
    最近更新 更多