我有两个模型,Post
和Comment
;许多评论属于一个帖子。我正在尝试以数组的形式访问与帖子相关的所有评论。
我有以下,它给出了一个集合。
$comments_collection = $post->comments()->get()
我如何将这个 $comments_collection
变成一个数组?有没有更直接的方式通过 eloquent 关系访问这个数组?
最佳答案
您可以使用 toArray() Eloquent 如下。
toArray
方法将集合转换为纯 PHP 数组。如果集合的值是 Eloquent 模型,模型也会被转换为数组
$comments_collection = $post->comments()->get()->toArray()
来自 Laravel 文档:
toArray also converts all of the collection's nested objects that are an instance of Arrayable to an array. If you want to get the raw underlying array, use the all method instead.
关于php - laravel 集合到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35284974/