Eloquent 的查詢結(jié)果會(huì)返回 IlluminateDatabaseEloquentCollection
,而使用 collect()
會(huì)返回 IlluminateSupportCollection
。而且,在 Laravel 文檔中,有如下信息:
大部分的 Eloquent 集合會(huì)返回新的「Eloquent 集合」實(shí)例,但是 pluck, keys, zip, collapse, flatten 和 flip 方法會(huì)返回 基礎(chǔ)集合 實(shí)例。
相應(yīng)的,如果一個(gè) map 操作返回一個(gè)不包含任何 Eloquent 模型的集合,那么它將會(huì)自動(dòng)轉(zhuǎn)換成基礎(chǔ)集合。
那么,這兩種 Collection,或者說是「基礎(chǔ)集合」和「Eloquent 集合」有什么區(qū)別呢?
認(rèn)證0級(jí)講師
看看源代碼,我們可以看到
<?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
也就是說,IlluminateDatabaseEloquentCollection
是IlluminateSupportCollection
的子類。
你說的這幾個(gè)方法,在IlluminateDatabaseEloquentCollection
中是這樣定義的,以pluck
為例。
/**
* 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);
}
而這里用到的toBase
函數(shù)在IlluminateDatabaseEloquentCollection
中沒有定義,而是在IlluminateSupportCollection
中定義了。那么在子類中沒有重寫的方法,就會(huì)調(diào)用父類的方法。我們看看toBase
在IlluminateSupportCollection
中是如何定義的。
/**
* Get a base Support collection instance from this collection.
*
* @return \Illuminate\Support\Collection
*/
public function toBase()
{
return new self($this);
}
看吧,是返回了new self($this)
,一個(gè)新的實(shí)例。由于這是在父類中的,自然返回的實(shí)例是IlluminateSupportCollection
了。IlluminateSupportCollection
中的pluck
定義是這樣的。
/**
* 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));
}
而在IlluminateSupportArr
中pluck
的定義是這樣的。
/**
* 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);
返回的是一個(gè)數(shù)組。
這樣IlluminateSupportCollection
中的new static(Arr::pluck)
,意思就是新建一個(gè)類的實(shí)例(new self
和new static
的區(qū)別詳見https://www.laravist.com/blog/post/php-new-static-and-new-self)。
怎么樣,現(xiàn)在明白了么?