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"?
ringa_lee2017-05-16 16:48:31
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 IlluminateDatabaseEloquentCollection
是IlluminateSupportCollection
.
The methods you mentioned are IlluminateDatabaseEloquentCollection
中是这样定义的,以pluck
for 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
中定义了。那么在子类中没有重写的方法,就会调用父类的方法。我们看看toBase
在IlluminateSupportCollection
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
中的pluck
The 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 IlluminateSupportArr
中pluck
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 self
和new static
can be found at https://www.laravist.com/blog/post/php-new-static-and-new-self).
How about it, do you understand now?