1
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?

LaravelでDBからデータを取得する際に返ってくる型

1
Posted at

LaravelでDBからデータを取得する際、返ってくる型は「Eloquentモデルを使うか、クエリビルダを使うか」で決まります。

Eloquentモデル → Modelクラスインスタンス

EloquentモデルUser::find()など)を使うと、Modelクラスのインスタンスが返ってきます。

// Modelインスタンスが返る(App\Models\User)
$user = User::find(1);           // → App\Models\Userオブジェクト
$users = User::get();            // → Illuminate\Database\Eloquent\Collection(中身はUserオブジェクト)

echo get_class($user);  // "App\Models\User"
$user->posts;           // リレーションが使える!
$user->save();          // モデルのメソッドが使える!

複数取得時もコレクションの中にModelオブジェクトが入っています。

foreach (User::get() as $user) {
    echo get_class($user);  // 毎回 "App\Models\User"
}

クエリビルダ → stdClassオブジェクト

クエリビルダDB::table())を使うと、stdClassオブジェクトが返ってきます。

// stdClassが返る
$user = DB::table('users')->where('id', 1)->first();  // → stdClassオブジェクト
$users = DB::table('users')->get();                   // → Illuminate\Support\Collection(中身はstdClass)

echo get_class($user);  // "stdClass"
$user->posts;           // エラー!リレーション使えない
$user->save();          // エラー!モデルのメソッド使えない

複数取得時もコレクションの中にstdClassが入っています。

foreach (DB::table('users')->get() as $user) {
    echo get_class($user);  // 毎回 "stdClass"
}

実装パターンの違いと使い分け

実装方法 1件取得 複数取得 リレーション使える? モデルのメソッド使える?
Eloquent User::find() Userモデル Collection[Userモデル]
クエリビルダ DB::table() stdClass Collection[stdClass]
1
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
1
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?