ChatGPT解决这个技术问题 Extra ChatGPT

laravel 集合到数组

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

我有以下内容,它提供了一个集合。

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

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


D
Drudge Rajen

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

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() 很好。另外,我已经用文档更新了答案。
e
eithed

使用 all() 方法 - 它旨在返回 Collection 项目:

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

但它在数组中吗?
是的@JovylleBermudez。它是一个对象数组
这对我来说是正确的解决方案,因为我需要一组模型,而不是一组数组。
İ
İlker Ergün

尝试这个:

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

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


如果查询没有任何记录,则 toArray() 不适用于 NULL 记录并返回错误。
A
Akshay Kulkarni

你可以做这样的事情

$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


W
Wolverine

使用 collect($comments_collection)

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


F
Ferhat KOÇER

尝试在数组中收集函数,例如:

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

这个方法可以帮助你

toArray() 和 collect()


如果查询没有任何记录,则 toArray() 不适用于 NULL 记录并返回错误。