国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Laravel 中兩類 Collection 的區(qū)別?
PHP中文網(wǎng)
PHP中文網(wǎng) 2017-05-16 16:46:31
0
1
738

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ū)別呢?

PHP中文網(wǎng)
PHP中文網(wǎng)

認(rèn)證0級(jí)講師

全部回復(fù)(1)
左手右手慢動(dòng)作

看看源代碼,我們可以看到

<?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

也就是說,IlluminateDatabaseEloquentCollectionIlluminateSupportCollection的子類。

你說的這幾個(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)用父類的方法。我們看看toBaseIlluminateSupportCollection中是如何定義的。

/**
 * 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));
}

而在IlluminateSupportArrpluck的定義是這樣的。

/**
 * 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 selfnew static的區(qū)別詳見https://www.laravist.com/blog/post/php-new-static-and-new-self)。

怎么樣,現(xiàn)在明白了么?

最新下載
更多>
網(wǎng)站特效
網(wǎng)站源碼
網(wǎng)站素材
前端模板