エンジニアのひよこ_level10

毎日更新してた人。たまに記事書きます。

【Laravel】Collectionのpluckと、クエリビルダのpluckの違い【490日目】

まずお詫びです

今日コード読んでいたら、この記事で書いたこと間違っていました!!!

www.nyamucoro.com

どう違うかは、該当記事で説明させていただきます。

Collectionのpluckと、クエリビルダのpluck?

クエリビルダでgetした後にできるCollectionに対してpluckするのと、
クエリビルダで組み立てている時にgetの代わりにするpluckは動作が異なります。

てか、戻り値が違います。

どう違うの?

Collectionのpluckは、supportのCollectionを返します。
ちなみに、EloquentのCollectionを使った場合も、supportのCollectionを返します。

クエリビルダでpluckすると、配列(array)を返します。

コード

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

vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php ```/* * Get an array with the values of a given column. * * @param string $column * @param string|null $key * @return array / public function pluck($column, $key = null) { $results = $this->get(is_null($key) ? [$column] : [$column, $key]);

    // If the columns are qualified with a table or have an alias, we cannot use
    // those directly in the "pluck" operations since the results from the DB
    // are only keyed by the column itself. We'll strip the table out here.
    return Arr::pluck(
        $results,
        $this->stripTableForPluck($column),
        $this->stripTableForPluck($key)
    );
}```