Larabel 4에서 새로운 빈 웅변 컬렉션을 수동으로 만드는 방법
Query Builder를 사용하지 않고 Larabel 4에서 새로운 웅변 컬렉션을 작성하려면 어떻게 해야 합니까?
이 있습니다.newCollection()
이 메서드는 설정된 결과를 쿼리할 때만 사용되므로 이 메서드에 의해 재정의될 수 있습니다.
빈 컬렉션을 만들고 나서 웅변적인 오브젝트로 채울까 생각 중이에요.어레이를 사용하지 않는 이유는 다음과 같은 웅변적인 컬렉션 방법을 좋아하기 때문입니다.contains
.
다른 대안이 있다면 꼭 듣고 싶습니다.
실제로 웅변적인 것은 아닙니다. 웅변적인 모델을 컬렉션에 추가하려면 다음과 같은 옵션을 사용할 수 있습니다.
라라벨 5에서는 도우미의 혜택을 받을 수 있습니다.
$c = collect(new Post);
또는
$c = collect();
$c->add(new Post);
오래된 Larabel 4의 답변
$c = new \Illuminate\Database\Eloquent\Collection;
그리고 넌 할 수 있어
$c->add(new Post);
또는 make를 사용할 수 있습니다.
$c = Collection::make(new Post);
라라벨 5부터요글로벌 기능을 사용합니다.collect()
$collection = collect([]); // initialize an empty array [] inside to start empty collection
이 구문은 매우 깨끗하며 숫자 인덱스를 원하지 않을 경우 다음과 같이 오프셋을 추가할 수도 있습니다.
$collection->offsetSet('foo', $foo_data); // similar to add function but with
$collection->offsetSet('bar', $bar_data); // an assigned index
사실 제가 발견한 건newCollection()
장래의 증거라고 생각합니다.
예:
$collection = (new Post)->newCollection();
이렇게 하면 나중에 모델을 위한 컬렉션 클래스를 만들기로 결정했을 때(여러 번 했듯이) 코드를 재팩터링하는 것이 훨씬 쉬워집니다.newCollection()
모델에서의 기능
Laravel > = 5.5
이것은 원래의 질문과는 관련이 없을지도 모르지만, 구글 검색의 첫 번째 링크 중 하나이기 때문에, 빈 컬렉션을 작성하는 방법을 찾고 있는 저 같은 사람에게 도움이 됩니다.
새로운 빈 컬렉션을 수동으로 작성하려면collect
도우미 방법은 다음과 같습니다.
$new_empty_collection = collect();
이 도우미는 에서 찾을 수 있습니다.Illuminate\Support\helpers.php
단편:
if (! function_exists('collect')) {
/**
* Create a collection from the given value.
*
* @param mixed $value
* @return \Illuminate\Support\Collection
*/
function collect($value = null)
{
return new Collection($value);
}
}
승인된 답변에 추가하기 위해 에일리어스를 작성할 수도 있습니다.config/app.php
'aliases' => array(
...
'Collection' => Illuminate\Database\Eloquent\Collection::class,
그럼 그냥 하면 되는 거야
$c = new Collection;
Laravel 5 및 Laravel 6에서는 다음 문제를 해결할 수 있습니다.Illuminate\Database\Eloquent\Collection
서비스 컨테이너에 모델을 추가합니다.
$eloquentCollection = resolve(Illuminate\Database\Eloquent\Collection::class);
// or app(Illuminate\Database\Eloquent\Collection::class). Whatever you prefer, app() and resolve() do the same thing.
$eloquentCollection->push(User::first());
larabel 내의 서비스 컨테이너에서 오브젝트를 해결하는 방법에 대한 자세한 내용은 https://laravel.com/docs/5.7/container#resolving를 참조하십시오.
이 방법을 사용하고 있습니다.
$coll = new Collection();
$coll->name = 'name';
$coll->value = 'value';
$coll->description = 'description';
일반 컬렉션으로 사용합니다.
ddscoll->name);
Injection Pattern(주입 패턴)과 After(후)를 사용하는 것이 좋습니다.$this->collection->make([])
보다new Collection
use Illuminate\Support\Collection;
...
// Inside of a clase.
...
public function __construct(Collection $collection){
$this->collection = $collection;
}
public function getResults(){
...
$results = $this->collection->make([]);
...
}
언급URL : https://stackoverflow.com/questions/23599584/how-to-manually-create-a-new-empty-eloquent-collection-in-laravel-4
'source' 카테고리의 다른 글
jQuery를 사용하여 DIV를 화면 중앙에 배치 (0) | 2023.01.29 |
---|---|
Java는 정적 초기화 블록에서 선택된 예외를 발생시키는 것을 허용하지 않는 이유는 무엇입니까? (0) | 2023.01.29 |
php.ini & SMTP= - 사용자 이름과 비밀번호 전달 방법 (0) | 2023.01.29 |
원칙의 사용방법 및 장소 및 장소 (0) | 2023.01.19 |
IntelliJ에서의 RegEx 백레퍼런스 (0) | 2023.01.19 |