Laravel 5.0 クエリービルダー

イントロダクション

データベースクエリービルダーはスラスラと書ける(fluent)便利なインターフェイスで、クエリーを作成し実行するために使用します。アプリケーションで行われるほとんどのデーターベース操作が可能で、サポートしている全データベースシステムに対し使用できます。

注意: Laravelクエリービルダーは、アプリケーションをSQLインジェクション攻撃から守るために、PDOパラメーターによるバインディングを使用します。バインドする文字列をクリーンにしてから渡す必要はありません。

SELECT

全レコードの取得

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

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

結果の分割

DB::table('users')->chunk(100, function($users)
{
    foreach ($users as $user)
    {
        //
    }
});

クロージャーからfalseを返すことにより、分割処理を中断できます。

DB::table('users')->chunk(100, function($users)
{
    //

    return false;
});

テーブルから1レコード取得

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

var_dump($user->name);

レコードの1カラム取得

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

カラム値をリストで取得

$roles = DB::table('roles')->lists('title');

このメソッド使用例ではroleのタイトルの配列がリターンされます。返される配列のキーカラムを指定することもできます。

$roles = DB::table('roles')->lists('title', 'name');

SELECT節の指定

$users = DB::table('users')->select('name', 'email')->get();

$users = DB::table('users')->distinct()->get();

$users = DB::table('users')->select('name as user_name')->get();

存在するクエリーにSELECT節を追加

$query = DB::table('users')->select('name');

$users = $query->addSelect('age')->get();

WHERE節の指定

$users = DB::table('users')->where('votes', '>', 100)->get();

OR文

$users = DB::table('users')
                    ->where('votes', '>', 100)
                    ->orWhere('name', 'John')
                    ->get();

WHERE BETWEEN

$users = DB::table('users')
                    ->whereBetween('votes', [1, 100])->get();

WHERE NOT BETWEENの使用

$users = DB::table('users')
                    ->whereNotBetween('votes', [1, 100])->get();

配列でWHERE INを指定

$users = DB::table('users')
                    ->whereIn('id', [1, 2, 3])->get();

$users = DB::table('users')
                    ->whereNotIn('id', [1, 2, 3])->get();

値が未設定のレコードを見つけるためにWHERE NULLを使用

$users = DB::table('users')
                    ->whereNull('updated_at')->get();

動的Where節

楽にwhere文を記述するため、magicメソッドを利用した「動的」なwhere文を使うこともできます。

$admin = DB::table('users')->whereId(1)->first();

$john = DB::table('users')
                    ->whereIdAndEmail(2, 'john@doe.com')
                    ->first();

$jane = DB::table('users')
                    ->whereNameOrAge('Jane', 22)
                    ->first();

ORDER BY、GROUP BY、HAVING

$users = DB::table('users')
                    ->orderBy('name', 'desc')
                    ->groupBy('count')
                    ->having('count', '>', 100)
                    ->get();

OFFSETとLIMIT

$users = DB::table('users')->skip(10)->take(5)->get();

JOIN

クエリービルダーはJOIN文を書くためにも使用できます。以下の例をご覧ください。

基本的なJOIN文

DB::table('users')
            ->join('contacts', 'users.id', '=', 'contacts.user_id')
            ->join('orders', 'users.id', '=', 'orders.user_id')
            ->select('users.id', 'contacts.phone', 'orders.price')
            ->get();

LEFT JOIN文

DB::table('users')
        ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
        ->get();

もっと複雑なJOIN節も指定できます。

DB::table('users')
        ->join('contacts', function($join)
        {
            $join->on('users.id', '=', 'contacts.user_id')->orOn(...);
        })
        ->get();

JOINに"where"節を使用したい場合は、joinの中でwhereorWhereを使用して下さい。2つのカラムを比べる代わりに、これらのメソッドは値に対してカラムを比較します。

DB::table('users')
        ->join('contacts', function($join)
        {
            $join->on('users.id', '=', 'contacts.user_id')
                 ->where('contacts.user_id', '>', 5);
        })
        ->get();

WHERE

パラメーターのグループ化

時々、"where exists"とかネストしたグループ分けのような、更に上級なSQL文を生成する必要があるでしょう。Laravelのクエリービルダーで上手く処理できます。

DB::table('users')
            ->where('name', '=', 'John')
            ->orWhere(function($query)
            {
                $query->where('votes', '>', 100)
                      ->where('title', '<>', 'Admin');
            })
            ->get();

クエリービルダーは以下のSQLを作成します。

select * from users where name = 'John' or (votes > 100 and title <> 'Admin')

EXISTS文

DB::table('users')
            ->whereExists(function($query)
            {
                $query->select(DB::raw(1))
                      ->from('orders')
                      ->whereRaw('orders.user_id = users.id');
            })
            ->get();

クエリービルダーは以下のSQLを作成します。

select * from users
where exists (
    select 1 from orders where orders.user_id = users.id
)

集計

また、クエリービルダーはcountmaxminavgsumなど多くの集計メソッドを提供しています。

集計メソッドの使用

$users = DB::table('users')->count();

$price = DB::table('orders')->max('price');

$price = DB::table('orders')->min('price');

$price = DB::table('orders')->avg('price');

$total = DB::table('users')->sum('votes');

SQL文の直接指定

たまにクエリーの中でSQLを直接使用したいことがあります。このようなSQLでは、文字をそのまま埋め込むだけですので、SQLインジェクションをされないように気をつけてください!エスケープなしのSQLを使用する場合はDB::rawメソッドを使用します。

SQLを直接使用

$users = DB::table('users')
                     ->select(DB::raw('count(*) as user_count, status'))
                     ->where('status', '<>', 1)
                     ->groupBy('status')
                     ->get();

INSERT

レコードの挿入

DB::table('users')->insert(
    ['email' => 'john@example.com', 'votes' => 0]
);

レコードを挿入し、自動増加したIDを取得

テーブルに自動増分IDがある場合はinsertGetIdを使い、レコードを挿入し、そのIDを取得してください。

$id = DB::table('users')->insertGetId(
    ['email' => 'john@example.com', 'votes' => 0]
);

注目: PostgreSQLにinsertGetIdメソッドを使用するときは、自動増分カラムの名前を"id"にしてください。

複数レコードの挿入

DB::table('users')->insert([
    ['email' => 'taylor@example.com', 'votes' => 0],
    ['email' => 'dayle@example.com', 'votes' => 0]
]);

UPDATE

レコード更新

DB::table('users')
            ->where('id', 1)
            ->update(['votes' => 1]);

カラム値の増加/減少

DB::table('users')->increment('votes');

DB::table('users')->increment('votes', 5);

DB::table('users')->decrement('votes');

DB::table('users')->decrement('votes', 5);

更に更新する追加のカラムも指定できます。

DB::table('users')->increment('votes', 1, ['name' => 'John']);

DELETE

レコード削除

DB::table('users')->where('votes', '<', 100)->delete();

全レコード削除

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

テーブルのTRUNCATE

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

クエリー結合

クエリービルダーは2つのクエリーを結合(union)させる手軽な手法を提供します。

$first = DB::table('users')->whereNull('first_name');

$users = DB::table('users')->whereNull('last_name')->union($first)->get();

unionAllメソッドも使用でき、unionと同じ使い方をします。

排他的ロック

クエリービルダーは、SELECT文で排他的ロックを行うための機能をいくつか持っています。

「共有ロック」でSELECT文を実行する場合は、sharedLockメソッドをクエリーで指定して下さい。

DB::table('users')->where('votes', '>', 100)->sharedLock()->get();

SELECT文を「専有ロック」で実行したい場合は、lockForUpdateメソッドをクエリーに使用します。

DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();

ドキュメント章別ページ

Artisan CLI

ヘッダー項目移動

注目:アイコン:ページ内リンク設置(リンクがないヘッダーへの移動では、リンクがある以前のヘッダーのハッシュをURLへ付加します。

移動

クリックで即時移動します。

設定

適用ボタンクリック後に、全項目まとめて適用されます。

カラーテーマ
和文指定 Pagination
和文指定 Scaffold
Largeスクリーン表示幅
インデント
本文フォント
コードフォント
フォント適用確認

フォントの指定フィールドから、フォーカスが外れると、当ブロックの内容に反映されます。EnglishのDisplayもPreviewしてください。

フォント設定時、表示に不具合が出た場合、当サイトのクッキーを削除してください。

バックスラッシュを含むインライン\Code\Blockの例です。

以下はコードブロックの例です。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * ユーザに関連する電話レコードを取得
     */
    public function phone()
    {
        return $this->hasOne('App\Phone');
    }
}

設定を保存する前に、表示が乱れないか必ず確認してください。CSSによるフォントファミリー指定の知識がない場合は、フォントを変更しないほうが良いでしょう。

キーボード・ショートカット

オープン操作

PDC

ページ(章)移動の左オフキャンバスオープン

HA

ヘッダー移動モーダルオープン

MS

移動/設定の右オフキャンバスオープン

ヘッダー移動

T

最初のヘッダーへ移動

E

最後のヘッダーへ移動

NJ

次ヘッダー(H2〜H4)へ移動

BK

前ヘッダー(H2〜H4)へ移動

その他

?

このヘルプページ表示
閉じる