イントロダクション
データベースクエリービルダーはスラスラと書ける(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の中でwhere
やorWhere
を使用して下さい。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
)
集計
また、クエリービルダーはcount
、max
、min
、avg
、sum
など多くの集計メソッドを提供しています。
集計メソッドの使用
$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();