0
1

Laravel のクエリビルダ⦅マニュアルのマニュアル⦆

Posted at

はじめに

 【PHP】のWebアプリケーションフレームワークである
 【Laravel = ララベル】のマニュアルを確認しました。

Laravel公式ドキュメントの日本語訳サイトは以下を参照。

データベースクエリの実行

テーブルからの全行の取得

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class UserController extends Controller
{
   public function index(): View
   {
       $users = DB::table('users')->get();

       return view('user.index', ['users' => $users]);
   }
}

【確認】全てをselect

<?php

namespace App\Http\Controllers;
 ⇒ 名前空間 ※1

use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
 ⇒ 名前空間の一部を取得 ※2

class UserController extends Controller
{

 ⇒ Controllerクラスを継承したクラスを定義 ※3


   /**
    * アプリケーションの全ユーザーをリスト表示
    */
   public function index(): View
   {
       $users = DB::table('users')->get();

   // 記述方法: DB::table('テーブル名')->get(getメソッドの引数);
      ⇒ etメソッドの引数 'フィールド名',  を
        指定しなければ全てのフィールドが取得される

       return view('user.index', ['users' => $users]);
   }
}

※1 namespace は名前空間とも呼ばれ、項目をカプセル化
※2 namespace で定義されたものを使うにはuse、つまりインポートという機能を使う
※3 LaravelのControllerクラスって何やってるの?


テーブルから単一の行/カラムを取得する
⇒ first()で、1レコードのみを取得


$user = DB::table('users')->where('name', 'John')->first();

return $user->email;

【確認】first()で、1レコードのみを取得


$user = DB::table('users')->where('name', 'John')->first();
 ⇒ nameカラムがJohnのレコードを1レコードのみ取得 ※4

return $user->email;
 ⇒ このメソッドは、単一のstdClassオブジェクトを返します。 ※5



※4 【laravel】データベースの操作:DBファサード編
※5 Laravelのクエリビルダについて


テーブルから単一の行/カラムを取得する
⇒ value で、1カラムのみを取得


$email = DB::table('users')->where('name', 'John')->value('email');

【確認】first で、1レコードのみを取得


$email = DB::table('users')->where('name', 'John')->value('email');
 ⇒ nameカラムがJohnのレコードのうち、emailカラムの値を取得 ※6

※6 Laravelでデータを扱う方法


テーブルから単一の行/カラムを取得する
⇒ 【確認】find で、id列の値で単一の行を取得


$user = DB::table('users')->find(3);


カラム値のリストの取得
⇒ 指定したキーの値をコレクションから取得


use Illuminate\Support\Facades\DB;

$titles = DB::table('users')->pluck('title');

foreach ($titles as $title) {
   echo $title;
}

【確認】指定したキーの値をコレクションから取得


use Illuminate\Support\Facades\DB;

$titles = DB::table('users')->pluck('title');
 ⇒ コレクションから役割名(title)を取得※7

foreach ($titles as $title) {
   echo $title;
}


※7 【laravel】データベースの操作:DBファサード編


カラム値のリストの取得
⇒ 指定したキーの値をコレクションから取得


$titles = DB::table('users')->pluck('title', 'name');

foreach ($titles as $name => $title) {
   echo $title;
}

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