「何気なく最初の値ほしいからって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の空が返ってくるのが
無かった感があって好きです。