2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

基本的なクエリビルダでの書き方

2
Posted at

✅ 要点サマリ

  • Laravel の Query Builder は “SQL を PHP で安全に書くラッパ”
  • 基本形は DB::table('テーブル')
  • SELECT / WHERE / INSERT / UPDATE / DELETE はそれぞれメソッドで書ける
  • where() / whereIn() / first() / pluck() が特に重要

✅ ステップバイステップ:基礎クエリ(超基本)

① *全件取得(SELECT )

DB::table('users')->get();

1件だけ取得(LIMIT 1)

DB::table('users')->first();

特定の条件で取得(WHERE)

DB::table('users')
    ->where('email', 'test@example.com')
    ->first();

複数条件(AND)

DB::table('users')
    ->where('status', 1)
    ->where('age', '>=', 20)
    ->get();

IN 句(whereIn)

スキル名から id を取るとき超便利。

DB::table('skills')
    ->whereIn('name', ['PHP', 'Laravel'])
    ->pluck('id');

→ 結果例:[1, 3]

特定カラムだけ取得(pluck)

DB::table('users')->pluck('email');

['a@example.com', 'b@example.com', ...]


🌟 よく使うパターン:id の取得

▶︎ 1件の id を取る

$id = DB::table('skills')
    ->where('name', 'PHP')
    ->value('id');

▶︎ 複数の id を取得(whereIn + pluck)

$ids = DB::table('skills')
    ->whereIn('name', $skillNames) // ['PHP', 'React', ...]
    ->pluck('id');                 // [1,5,11,...]

🌟 INSERT(データ登録)

1件の Insert

DB::table('projects')->insert([
    'title' => '新しい案件',
    'description' => '説明文',
    'created_at' => now(),
    'updated_at' => now(),
]);

insertGetId(作成したレコードの id を取得)

$projectId = DB::table('projects')->insertGetId([
    'title' => '新しい案件',
    'created_at' => now(),
    'updated_at' => now(),
]);

🌟 UPDATE(データ更新)

DB::table('projects')
    ->where('id', $projectId)
    ->update([
        'title' => 'タイトル更新',
        'updated_at' => now(),
    ]);

🌟 DELETE(削除)

DB::table('projects')
    ->where('id', $id)
    ->delete();

🌟 ORDER / LIMIT など

ORDER BY

DB::table('users')->orderBy('created_at', 'desc')->get();

LIMIT

DB::table('users')->limit(10)->get();

🎯 設計の意図 & 注意点

  • Query Builder は SQL を直接書かず、安全に DB を操作できる
  • where や pluck などは Eloquent とほぼ同じ
  • Repository 層では Query Builder を使うと柔軟で安全
  • SQL インジェクション対策が自動で効くので安心
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?