What is the difference between two types of Collections in Laravel?
PHP中文网
PHP中文网 2017-05-16 16:46:31
0
1
598

Eloquent's query results will return Illuminate\Database\Eloquent\Collection, while using collect() will return Illuminate\Support\Collection. Moreover, in the Laravel documentation, there is the following information:

Most Eloquent collections will return new "Eloquent collection" instances, but the pluck, keys, zip, collapse, flatten and flip methods will return base collection instances.

Correspondingly, if a map operation returns a collection that does not contain any Eloquent model, it will be automatically converted to a base collection.

So, what is the difference between these two Collections, or "Basic Collection" and "Eloquent Collection"?

PHP中文网
PHP中文网

认证0级讲师

reply all(1)
左手右手慢动作

Looking at the source code, we can see

<?php

namespace Illuminate\Database\Eloquent;

use LogicException;
use Illuminate\Support\Arr;
use Illuminate\Contracts\Queue\QueueableCollection;
use Illuminate\Support\Collection as BaseCollection;

class Collection extends BaseCollection implements QueueableCollection

In other words, a subclass of IlluminateDatabaseEloquentCollectionIlluminateSupportCollection.

The methods you mentioned are IlluminateDatabaseEloquentCollection中是这样定义的,以pluckfor example.

/**
 * Get an array with the values of a given key.
 *
 * @param  string  $value
 * @param  string|null  $key
 * @return \Illuminate\Support\Collection
 */
public function pluck($value, $key = null)
{
    return $this->toBase()->pluck($value, $key);
}

And how is the definition used in toBase函数在IlluminateDatabaseEloquentCollection中没有定义,而是在IlluminateSupportCollection中定义了。那么在子类中没有重写的方法,就会调用父类的方法。我们看看toBaseIlluminateSupportCollection used here.

/**
 * Get a base Support collection instance from this collection.
 *
 * @return \Illuminate\Support\Collection
 */
public function toBase()
{
    return new self($this);
}

Look, it’s returnednew self($this),一个新的实例。由于这是在父类中的,自然返回的实例是IlluminateSupportCollection了。IlluminateSupportCollection中的pluckThe definition is like this.

/**
 * Get the values of a given key.
 *
 * @param  string|array  $value
 * @param  string|null  $key
 * @return static
 */
public function pluck($value, $key = null)
{
    return new static(Arr::pluck($this->items, $value, $key));
}

And the definition of IlluminateSupportArrpluck is this.

/**
 * Pluck an array of values from an array.
 *
 * @param  array  $array
 * @param  string|array  $value
 * @param  string|array|null  $key
 * @return array
 */
public static function pluck($array, $value, $key = null);

What is returned is an array.
The difference between this IlluminateSupportCollection中的new static(Arr::pluck),意思就是新建一个类的实例(new selfnew static can be found at https://www.laravist.com/blog/post/php-new-static-and-new-self).

How about it, do you understand now?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template