イントロダクション
データベースクエリービルダーは便利で、スラスラと書ける(fluent)インターフェイスで、クエリーを作成し、実行することができます。アプリケーションで行われるデーターベース操作のほとんどが可能で、サポートしているデータベースシステム全部に対して使用できます。
注意:Laravelのクエリービルダーは、アプリケーションをSQLインジェクション攻撃から守るために、PDOパラメーターによるバインディングを使用します。バインドする文字列をクリーンにしてから渡す必要はありません。
SELECT
テーブルから全レコードを取得する
$users = DB::table('users')->get();
foreach ($users as $user)
{
var_dump($user->name);
}
テーブルから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', array(1, 100))->get();
WHERE NOT BETWEENの使用
$users = DB::table('users')
->whereNotBetween('votes', array(1, 100))->get();
配列でWHERE INを使用する
$users = DB::table('users')
->whereIn('id', array(1, 2, 3))->get();
$users = DB::table('users')
->whereNotIn('id', array(1, 2, 3))->get();
値が設定されていないレコードを見つけるためWHERE NULLを使用する
$users = DB::table('users')
->whereNull('updated_at')->get();
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(
array('email' => 'john@example.com', 'votes' => 0)
);
テーブルにレコードを挿入し、自動増加したIDを取得する
テーブルに自動増分IDがある場合はinsertGetId
を使い、レコードを挿入し、そのIDを取得してください。
$id = DB::table('users')->insertGetId(
array('email' => 'john@example.com', 'votes' => 0)
);
注目:PostgreSQLにinsertGetIdメソッドを使用するときには、自動増分カラムの名前は"id"にしてください。
テーブルに複数のレコードを挿入する
DB::table('users')->insert(array(
array('email' => 'taylor@example.com', 'votes' => 0),
array('email' => 'dayle@example.com', 'votes' => 0),
));
UPDATE
テーブルのレコードを更新する
DB::table('users')
->where('id', 1)
->update(array('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, array('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();
クエリーのキャッシュ
remember
かrememberForever
を使用して、クエリー結果を簡単にキャッシュできます。
$users = DB::table('users')->remember(10)->get();
この例では、クエリー結果は10分間キャッシュされます。その間、結果はキャッシュされ、データベースに対してそのクエリーは実行されません。結果はアプリケーションに指定されているデフォルトキャッシュドライバーからロードされます。
サポートされているキャッシュドライバーを使用している場合、タグをキャッシュすることも可能です。
$users = DB::table('users')->cacheTags(array('people', 'authors'))->remember(10)->get();