【发布时间】:2016-12-11 00:22:40
【问题描述】:
给定 Eloquent Models 的 Collection,它们是 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->all()? -
你试过each()方法吗?