您可以如下使用 eloquent 的 toArray()。
toArray
方法将集合转换为纯 PHP 数组。如果集合的值是 Eloquent 模型,模型也会被转换为数组
$comments_collection = $post->comments()->get()->toArray()
来自 Laravel 文档:
toArray 还将集合中所有作为 Arrayable 实例的嵌套对象转换为数组。如果要获取原始底层数组,请改用 all 方法。
使用 all()
方法 - 它旨在返回 Collection 项目:
/**
* Get all of the items in the collection.
*
* @return array
*/
public function all()
{
return $this->items;
}
尝试这个:
$comments_collection = $post->comments()->get()->toArray();
看看这可以帮助你
toArray() method in Collections
你可以做这样的事情
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
参考是 https://laravel.com/docs/5.1/collections#method-toarray
最初来自 Laracasts 网站 https://laracasts.com/discuss/channels/laravel/how-to-convert-this-collection-to-an-array
使用 collect($comments_collection)
。
否则,尝试 json_encode($comments_collection)
转换为 json。
尝试在数组中收集函数,例如:
$comments_collection = collect($post->comments()->get()->toArray());
这个方法可以帮助你
toArray() 和 collect()
不定期副业成功案例分享
\Illuminate\Contracts\Support\Arrayable
,它们也会被递归地转换为数组。这包括 Eloquent 模型。->toArray()
不会将集合转换为数组,而是将整个内容转换为数组,包括集合中的项目。->all()
应该是公认的答案。toArray()
很好。另外,我已经用文档更新了答案。