0
0

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.

Laravel: Eloquentでカラムの存在チェックする際のtips

0
Last updated at Posted at 2022-03-01

Laravelプロジェクトのdbで任意のカラムが存在するかチェックをする際どうするか。

Builder

$user->posts()->count()
で確認していることが多かった。
これだと、全ての行を数え上げしてしまうので行数が多いと速度が落ちる。
Builderの場合の存在チェックはexists()を用いることで条件に一致した瞬間検索を打ち切ることから速度が速くなる。

Collection

ではCollectionも同様に$posts->count()ではなくexists似たような関数の$posts->contains()を使うべきか。

答えは$posts->count()
count()はO(1)だが、contains()はO(n)らしい。

countがO(1)である解説
https://zudoh.com/php/implementation-of-count-function

さてここでようやく実装が見えましたね。
count関数の行っていることはhashtable構造体のnNumOfElementsを返却しているだけなのです。

Collectionの計算量
https://tech.innovator.jp.net/entry/2018/09/27/190322

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?