9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

QueryBuilderのfirst()の動きを調べてみた

Last updated at Posted at 2017-03-16

「何気なく最初の値ほしいからってfirst()してるけど、裏で実は全部取得してんじゃないの!?」
とかいう疑念が湧いたので調べました

first()の基本的挙動

役割

クエリを作った後、1件に絞って値の取得をする。

コード

    /**
     * Execute the query and get the first result.
     *
     * @param  array   $columns
     * @return \stdClass|array|null
     */
    public function first($columns = ['*'])
    {
        return $this->take(1)->get($columns)->first();
    }

take()

limitを発行してます
ここでは引数が1なので1件取得の意味

get()

おなじみです。
値を取得するぞーーーの気持ちです
返ってくるのはcollect()です

first()

再帰呼び出し!?って思っちゃいますが、違います
collectionのfirst()です
get()からはcollect([0 => 'hoge'])って返ってきてるので
これをcollect(['hoge'])にしてる(一緒じゃんと思いますが)

つまりfirst()は....

ちゃんとlimitのクエリを発行してるので
全件取得とか危険なことはしてない
※デバッカーで発行クエリを見れば分かる話でした

5.1と5.3の挙動の違い

じつはfirst()は5.1の挙動と5.3の挙動で進化してる

5.1

   /**
     * Execute the query and get the first result.
     *
     * @param  array   $columns
     * @return mixed|static
     */
    public function first($columns = ['*'])
    {
        $results = $this->take(1)->get($columns);
        return count($results) > 0 ? reset($results) : null;
    }

5.3

    /**
     * Execute the query and get the first result.
     *
     * @param  array   $columns
     * @return \stdClass|array|null
     */
    public function first($columns = ['*'])
    {
        return $this->take(1)->get($columns)->first();
    }

8.x (追記)

8になっても、だいたい変わらずでした
しいていえば、書かれたファイルが移動したのと
Model|object|static|null と型が増えたところでしょうか

    /**
     * Execute the query and get the first result.
     *
     * @param  array|string  $columns
     * @return \Illuminate\Database\Eloquent\Model|object|static|null
     */
    public function first($columns = ['*'])
    {
        return $this->take(1)->get($columns)->first();
    }

何が違う

クエリ実行結果が得られなかった時の挙動が変わりました

結果が無かったら
5.1ではnull
5.3から collect([])が返ってくるようです

個人的には5.3のcollectの空が返ってくるのが
無かった感があって好きです。

9
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?