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

查看:73
本文介绍了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变成一个数组?是否有更直接的方法通过雄辩的关系访问此数组?

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屋!

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