从laravel集合中获取模型数组


Get array of Models from a laravel collection

给定Eloquent ModelsCollection,即Arrayable,我如何获得这些对象的数组?

如果我在集合上调用->toArray(),它会给我一个嵌套的关联数组,破坏模型。

如果我把它投射到一个数组中,我会得到一个非常奇怪的东西:

array:1 [▼
  "'x00*'x00items" => array:1 [▼
    "temp" => HistorySeries {#374 ▼
      #table: "history_series_hse"
      #primaryKey: "id_hse"
      #connection: "mysql"
      +timestamps: false
      <...snip...>
    }
  ]
]

然后是这个,但我真的不喜欢它(它有效(:

    $reflection = new ReflectionClass($coll);
    $property = $reflection->getProperty('items');
    $property->setAccessible(true);
    $array = $property->getValue($coll);

或者我可以用foreach循环提取它,但这很难看。有什么好办法吗?

Collection只是一个标准数组的包装器。要获得该标准数组,请在Collection上调用all()方法。

// Collection of Item models
$itemsCollection = Item::all();
// standard array of Item models
$itemsArray = $itemsCollection->all();

不要试图强制转换为数组,而是保持Collection的完整性,并使用像mapeach这样的高阶函数来完成您需要的操作。

例如:

$multiplied = $collection->map(function ($item, $key) {
    return $item * 2;
});
$multiplied->all();

您没有指定实际需要对数据做什么,所以这只是文档中的一个松散示例。

你不能强制转换为数组并保持模型的完整性,这是行不通的。