php - laravel 集合到数组

标签 php arrays laravel eloquent

我有两个模型,PostComment;许多评论属于一个帖子。我正在尝试以数组的形式访问与帖子相关的所有评论。

我有以下,它给出了一个集合。

$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/

相关文章:

php - 如何连接 laravel 集合的值

检查指针数组中的指针是否为空

arrays - Float 类型的值没有枚举成员

php - Laravel 5 : How to create a custom attribute for a collection, 然后用它排序

php - 如何在单个 mysql 查询中集成日期检查功能?

javascript - 如何在jquery中插入php脚本?

c++排序算法难度与数组长度

mysql - 在 Laravel 中使用 foreach 加入查询

php - 通过 href 发送变量

php - 在 mysql 中,如何选择字段的数字部分?