laravel 集合到数组 [英] laravel collection to array

查看:65
本文介绍了laravel 集合到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 变成一个数组?有没有更直接的方式通过 eloquent 关系访问这个数组?

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 的实例)转换为数组.如果您想获取原始底层数组,请改用 all 方法.

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.

这篇关于laravel 集合到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆