Eloquent에서 여러 건의 모델을 가져오면 결과는 Illuminate\Database\Eloquent\Collection으로 반환됩니다.
이 클래스는 Illuminate\Support\Collection을 상속하고 있으므로 베이스 컬렉션의 메서드를 그대로 사용할 수 있습니다.
use App\Models\User;$users = User::where('active', true)->get();foreach ($users as $user) { echo $user->name;}
먼저 기본이 되는 컬렉션과 Eloquent 입문을 익혀 두면 Eloquent 컬렉션의 확장 포인트를 이해하기 쉬워집니다.
가져온 모델 그룹의 기본 키에 대한 whereIn 쿼리를 만들어 일괄 갱신이나 삭제에 사용할 수 있습니다.
use App\Models\User;// 우선 조건에 일치하는 사용자를 가져온다$vipUsers = User::where('status', 'VIP')->get();// 컬렉션 대상만 일괄 갱신$vipUsers->toQuery()->update([ 'status' => 'Administrator',]);
개별 save() 루프보다 toQuery()로 일괄 쿼리로 변환하면 실제 운용에서의 성능과 가독성을 양립하기 쉬워집니다.
<?phpnamespace App\Models;use App\Support\UserCollection;use Illuminate\Database\Eloquent\Collection;use Illuminate\Database\Eloquent\Model;class User extends Model{ public function newCollection(array $models = []): Collection { $collection = new UserCollection($models); if (Model::isAutomaticallyEagerLoadingRelationships()) { $collection->withRelationshipAutoloading(); } return $collection; }}
newCollection() 또는 #[CollectedBy]를 정의하면, 일반적으로 Eloquent\Collection이 반환되는 상황에서 커스텀 컬렉션이 반환되게 됩니다.
모든 모델에 적용하고 싶은 경우에는 공통 베이스 모델에서 newCollection()을 정의합니다.