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?

Laravelの all() / with() / where() の違いをしっかり理解する【初心者向けORM入門】

Posted at

はじめに

LaravelでEloquent(ORM)を使っていると、以下のようなメソッドを頻繁に見かけます:

User::all();
Post::with('user')->get();
User::where('email', $email)->first();

これらはすべて モデルを通じてデータベースにアクセスするためのメソッドですが、意味や使い方がそれぞれ異なります。

この記事では、初心者が混乱しやすい all()・with()・where() の違いを、実際のコード例を交えてわかりやすく解説します。

①all() の意味と使い方

User::all();

概要:

  • テーブルの全レコードを取得するメソッド
  • SELECT * FROM users に相当

戻り値:

  • Illuminate\Database\Eloquent\Collection(コレクション)

使用例:

$users = User::all();

foreach ($users as $user) {
    echo $user->name;
}

注意:

  • 件数が多いテーブルではパフォーマンスに注意(大量にメモリ消費)

② with() の意味と使い方(リレーションの事前読み込み)

Post::with('user')->get();

概要:

  • リレーション先のデータを一緒に取得(Eager Loading)
  • N+1問題 を防ぐためによく使う

使用例:

$posts = Post::with('user')->get();

foreach ($posts as $post) {
    echo $post->user->name . ':' . $post->title;
}

SQL的には:

SELECT * FROM posts;
SELECT * FROM users WHERE id IN (...);

→ user() が belongsTo(User::class) として定義されている必要あり

③where() の意味と使い方(絞り込み)

User::where('email', 'example@example.com')->first();

概要:

  • 条件を指定してデータを絞り込む
  • 複数条件もOK

使用例:

 $adminUsers = User::where('role', 'admin')->get();
$user = User::where('email', $email)->first();

チェーンも可能:

$posts = Post::where('status', 'published')
             ->where('category_id', 2)
             ->get();

④比較まとめ

IMG_4032.jpeg

⑤よくある勘違い

Q. User::all()->where(...) はOK?
NGです。

all() はすでに全件を取得してコレクションになっているため、where() はコレクションのフィルタになってしまいます。
→ つまり、DBに対して絞り込みは行われません!

正しい使い方:

// DBで絞り込む
User::where('role', 'admin')->get();

⑥おまけ:メソッドチェーンの組み合わせ例

$posts = Post::with('user')
             ->where('status', 'published')
             ->orderBy('created_at', 'desc')
             ->get();

→ 投稿とユーザーを一緒に取得し、published 状態のものだけを新着順で並べる

⑦まとめ

  • all() → 全件取得(簡単だけど注意が必要)
  • with() → リレーションを一緒に取得(N+1問題対策)
  • where() → 条件を指定して絞り込み

Eloquentのメソッドは、単体だけでなくチェーンして組み合わせることで、柔軟で読みやすいクエリが書けます!

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?