laravel集合到数组 [英] laravel collection to array
问题描述
我有两个模型,Post
和Comment
;许多评论属于一个帖子.我正在尝试以数组形式访问与帖子相关的所有评论.
I have two models, Post
and Comment
; many comments belong to a single post. I'm trying to access all comments associated with a post as an array.
我有以下内容,提供了一个集合.
I have the following, which gives a collection.
$comments_collection = $post->comments()->get()
我如何将这个$comments_collection
变成一个数组?是否有更直接的方法通过雄辩的关系访问此数组?
How would I turn this $comments_collection
into an array? Is there a more direct way of accessing this array through eloquent relationships?
推荐答案
您可以使用 toArray ()雄辩如下.
You can use toArray() of eloquent as below.
toArray
方法将集合转换为纯PHP数组.如果集合的值是Eloquent模型,则这些模型也将转换为数组
The toArray
method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays
$comments_collection = $post->comments()->get()->toArray()
来自Laravel文档:
From Laravel Docs:
toArray还将所有可作为Arrayable实例的集合的嵌套对象转换为数组.如果要获取原始基础数组,请改用所有方法.
这篇关于laravel集合到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!