【问题标题】:laravel collection to arraylaravel 集合到数组
【发布时间】:2016-05-19 00:29:35
【问题描述】:

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

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

$comments_collection = $post->comments()->get()

我如何将这个$comments_collection 变成一个数组?有没有更直接的方式通过 eloquent 关系访问这个数组?

【问题讨论】:

    标签: php arrays laravel eloquent


    【解决方案1】:

    您可以使用 toArray() 的 eloquent 如下。

    toArray 方法将集合转换为普通的 PHP 数组。如果集合的值是 Eloquent 模型,模型也会被转换为数组

    $comments_collection = $post->comments()->get()->toArray()
    

    来自 Laravel 文档:

    toArray 还将集合中所有作为 Arrayable 实例的嵌套对象转换为数组。如果要获取原始底层数组,请改用all 方法。

    【讨论】:

    • 有时候这个方法在没有数据的时候会抛出异常。
    • 你能告诉我它引发期望的情况吗?我尝试使用空数据,但没有抛出异常
    • Nit-pick:如果数组元素实现了\Illuminate\Contracts\Support\Arrayable,它们也会被递归地转换为数组。这包括 Eloquent 模型。
    • 这不应该是最佳答案。 ->toArray() 不会将集合转换为数组,它会将整个内容转换为数组,包括集合的项目。 ->all() 应该是公认的答案。
    • @SebastienC。 OP 询问了将集合转换为数组的方法。所以,toArray() 很好。另外,我已经用文档更新了答案。
    【解决方案2】:

    使用all() 方法 - 它旨在返回集合项:

    /**
     * Get all of the items in the collection.
     *
     * @return array
     */
    public function all()
    {
        return $this->items;
    }
    

    【讨论】:

    • 但它在数组中吗?
    • 是的@JovylleBermudez。它是一个对象数组
    【解决方案3】:

    试试这个:

    $comments_collection = $post->comments()->get()->toArray();
    

    看到这个可以帮助你
    toArray() method in Collections

    【讨论】:

    • 如果查询没有任何记录,则 toArray() 对 NULL 记录不起作用并返回错误。
    【解决方案4】:

    你可以这样做

    $collection = collect(['name' => 'Desk', 'price' => 200]);
    $collection->toArray();
    

    参考是https://laravel.com/docs/5.1/collections#method-toarray

    原文来自 Laracasts 网站https://laracasts.com/discuss/channels/laravel/how-to-convert-this-collection-to-an-array

    【讨论】:

      【解决方案5】:

      使用collect($comments_collection)

      否则,请尝试json_encode($comments_collection) 转换为 json。

      【讨论】:

        【解决方案6】:

        在数组中尝试 collect 函数,例如:

        $comments_collection = collect($post->comments()->get()->toArray());
        

        这些方法可以帮助你

        toArray()collect()

        【讨论】:

        • 如果查询没有任何记录,则 toArray() 对 NULL 记录不起作用并返回错误。
        猜你喜欢
        • 2018-09-22
        • 2018-09-23
        • 2015-07-07
        • 2017-03-07
        • 2018-12-15
        • 2018-07-22
        • 1970-01-01
        • 2016-01-22
        • 1970-01-01
        相关资源
        最近更新 更多