2016-08-04 94 views
0

给定Collection Eloquent Models,它们是Arrayable,如何获取这些对象的数组?获取laravel集合中的模型数组

如果我在集合上调用->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循环提取它,但这很丑陋。任何不错的方式?

+0

试试'$ collection-> all()'? – ceejayoz

+0

您是否尝试过[每个()](https://laravel.com/docs/5.2/collections#method-each)方法? –

回答

2

Collection只是一个标准阵列的包装。要获得该标准阵列,请致电Collection上的all()方法。

// Collection of Item models 
$itemsCollection = Item::all(); 

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

不要尝试投射阵列,而是保持您的集合完好,并使用高阶函数,如mapeach来做你所需要的。

例:

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

$multiplied->all(); 

不指定你真正需要的数据这样做,这只是一个松散的例子from the docs

您不能转换为数组并保持模型不变,它将不起作用。

+0

“你不能得到一个数组并保持模型完好无损,这是行不通的。”这是不正确的。从一组模型中获取一系列模型是完全可能的。 – ceejayoz

+0

我意识到这不是我想说的。 –