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"?
Looking at the source code, we can see
In other words, a subclass of
IlluminateDatabaseEloquentCollection
是IlluminateSupportCollection
.The methods you mentioned are
IlluminateDatabaseEloquentCollection
中是这样定义的,以pluck
for example.And how is the definition used in
toBase
函数在IlluminateDatabaseEloquentCollection
中没有定义,而是在IlluminateSupportCollection
中定义了。那么在子类中没有重写的方法,就会调用父类的方法。我们看看toBase
在IlluminateSupportCollection
used here.Look, it’s returned
new self($this)
,一个新的实例。由于这是在父类中的,自然返回的实例是IlluminateSupportCollection
了。IlluminateSupportCollection
中的pluck
The definition is like this.And the definition of
IlluminateSupportArr
中pluck
is this.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?