source

배열에 대한 라라벨 컬렉션

bestscript 2022. 12. 12. 21:14

배열에 대한 라라벨 컬렉션

저는 두 가지 모델이 있습니다.Post그리고.Comment; 많은 코멘트가 1개의 투고에 속합니다.게시물과 관련된 모든 코멘트에 배열로 액세스하려고 합니다.

저는 수집을 할 수 있는 다음과 같은 것을 가지고 있습니다.

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

이걸 어떻게 돌리지?$comments_collection배열할 수 있나요?웅변적인 관계를 통해 이 어레이에 직접 접근할 수 있는 방법이 있습니까?

다음과 같이 allustive의 toArray()를 사용할 수 있습니다.

toArraymethod는 컬렉션을 일반 PHP 배열로 변환합니다.컬렉션 값이 Archent 모델인 경우 모델도 배열로 변환됩니다.

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

Laravel Docs에서:

toArray는 또한 Arrayable 인스턴스인 컬렉션의 모든 중첩된 개체를 배열로 변환합니다.원시 기본 어레이를 가져오려면 대신 all 방법을 사용하십시오.

사용하다all()메서드 - 컬렉션 항목을 반환하도록 설계되었습니다.

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

이것을 시험해 보세요.

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

이것이 도움이 되는 것을 확인하세요.
컬렉션 내의 toArray() 메서드

당신은 이런 것을 할 수 있다.

$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에서 작성되었습니다.

사용하다collect($comments_collection).

그렇지 않으면 시도해 보세요.json_encode($comments_collection)json으로 변환합니다.

다음과 같이 배열에서 수집 기능을 시도합니다.

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

이 방법이 도움이 됩니다.

toArray() 및 collect()

언급URL : https://stackoverflow.com/questions/35284974/laravel-collection-to-array