LoginSignup
405
376

More than 3 years have passed since last update.

【Laravel】DB登録値取得時のfind()、get()、first()の返り値早見表

Last updated at Posted at 2017-12-04

よく忘れるのでメモ

find()

App\Model::find(1) の返り値はModelのオブジェクト

get()

App\Model::where('id',1)->get() の返り値はCollectionクラス
(中身はModelのオブジェクト。ゆえにforeach()で回せば各々の値を取得できる。)

first()

App\Model::where('id',1)->first() の返り値はModelのオブジェクト

※もしなかった場合はNULLを返す

以下tinker(laravel用REPL)で実行した際の様子

$ php artisan tinker
New version is available (current: v0.8.14, latest: v0.8.15)
>>> App\Model::find(1)
=> App\Model{#458
     id: 1,
     name: "モデル1",
     created_at: "2017-11-30 07:32:29",
     updated_at: "2017-11-30 07:32:29",
   }

>>> App\Model::where('id',1)->get()
=> Illuminate\Database\Eloquent\Collection {#449
     all: [
       App\Model{#448
         id: 1,
         name: "モデル1",
         created_at: "2017-11-30 07:32:29",
         updated_at: "2017-11-30 07:32:29",
       },
     ],
   }

>>> App\Model::where('id',1)->first()
=> App\Model{#470
     id: 1,
     name: "モデル1",
     created_at: "2017-11-30 07:32:29",
     updated_at: "2017-11-30 07:32:29",
   }

>>>

ちなみに:where()

ちなみに

App\Model::where('id',1)の返り値はBuilderクラス

>>> App\Model::where('id',1)
=> Illuminate\Database\Eloquent\Builder {#462}
>>>

そんで:all()

そんでApp\Model::all() の返り値はCollectionクラス

>>> App\Model::all()
=> Illuminate\Database\Eloquent\Collection

もっとくわしく

おわり

以下もどうぞ

405
376
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
405
376