我有两个模型,Post
和Comment
;许多评论属于一个帖子。我正在尝试以数组形式访问与帖子相关的所有评论。
我有以下内容,它给出了一个集合。
$comments_collection = $post->comments()->get()
如何将此$comments_collection
转换为数组?有没有更直接的方法可以通过雄辩的关系访问这个数组?
你可以使用 toArray() 的雄辩,如下所示。
toArray
方法将集合转换为普通的 PHP 数组。如果集合的值是 Eloquent 模型,则模型也将转换为数组
$comments_collection = $post->comments()->get()->toArray()
来自 Laravel Docs:
toArray 还将作为 Arrayable 实例的所有集合嵌套对象转换为数组。如果要获取原始基础数组,请改用 all 方法。
使用all()
方法 - 它旨在返回集合的项目:
/**
* Get all of the items in the collection.
*
* @return array
*/
public function all()
{
return $this->items;
}
试试这个:
$comments_collection = $post->comments()->get()->toArray();
看到这个可以帮助你
toArray() 方法在 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。
只需在集合上执行 all() 返回一个数组,如下所示:
$comments_collection = $post->comments()->all();
我使用的是 Laravel 10.5.0,这对我来说效果很好。
对于嵌套集合(例如,当我们调用查询生成器 get 方法时),我们可以通过向集合类型添加一个宏来简化事情。 我们假设我们的集合是 stdClass 对象的集合。
为此,请将此代码添加到 AppServiceProvider
中的 boot()
方法:
Collection::macro('toNestedArray', function () {
return $this->transform(function ($item, int $key) {
return (array)$item;
});
});
请注意,此代码只会将一级嵌套的 stdClass 转换为数组。 您可以根据需要调整代码
尝试在数组中收集函数,如下所示:
$comments_collection = collect($post->comments()->get()->toArray());
此方法可以帮助您
toArray() with collect()