データベースの使い方(Laravelデータベースコンポーネントに基づく)

すべての行を取得

<?php
namespace app\controller;

use support\Request;
use support\Db;

class UserController
{
    public function all(Request $request)
    {
        $users = Db::table('users')->get();
        return view('user/all', ['users' => $users]);
    }
}

指定した列を取得

$users = Db::table('user')->select('name', 'email as user_email')->get();

1行を取得

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

1列を取得

$titles = Db::table('roles')->pluck('title');

指定したidフィールドの値をインデックスとして使用

$roles = Db::table('roles')->pluck('title', 'id');

foreach ($roles as $id => $title) {
    echo $title;
}

単一の値(フィールド)を取得

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

重複を除去

$email = Db::table('user')->select('nickname')->distinct()->get();

結果をチャンクで取得

数千件のデータベースレコードを処理する必要がある場合、一度にこれらのデータを読み込むのは時間がかかり、メモリ超過を引き起こす可能性があります。この場合、 chunkById メソッドを使用することをお勧めします。このメソッドは、結果セットの小さな部分を一度に取得し、それを クロージャ 関数に渡して処理します。例えば、すべての users テーブルのデータを一度に 100 件ずつ処理することができます:

Db::table('users')->orderBy('id')->chunkById(100, function ($users) {
    foreach ($users as $user) {
        //
    }
});

クロージャ内で false を返すことで、チャンクの結果の取得を終了できます。

Db::table('users')->orderBy('id')->chunkById(100, function ($users) {
    // レコードを処理...

    return false;
});

注意:コールバック内でデータを削除しないでください。それにより、一部のレコードが結果セットに含まれない可能性があります。

集計

クエリビルダーは、count、max、min、avg、sumなどのさまざまな集計メソッドも提供しています。

$users = Db::table('users')->count();
$price = Db::table('orders')->max('price');
$price = Db::table('orders')->where('finalized', 1)->avg('price');

レコードの存在を確認

return Db::table('orders')->where('finalized', 1)->exists();
return Db::table('orders')->where('finalized', 1)->doesntExist();

生の式

プロトタイプ

selectRaw($expression, $bindings = [])

時にはクエリで生の式を使用する必要がある場合があります。selectRaw()を使用して生の式を作成できます:

$orders = Db::table('orders')
                ->selectRaw('price * ? as price_with_tax', [1.0825])
                ->get();

同様に、whereRaw() orWhereRaw() havingRaw() orHavingRaw() orderByRaw() groupByRaw()の生の式メソッドも提供されています。

Db::raw($value)も生の式を作成するために使用されますが、バインドされたパラメータの機能はなく、使用時にはSQLインジェクションの問題に注意が必要です。

$orders = Db::table('orders')
                ->select('department', Db::raw('SUM(price) as total_sales'))
                ->groupBy('department')
                ->havingRaw('SUM(price) > ?', [2500])
                ->get();

Join文

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

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

// rightJoin
$users = Db::table('users')
            ->rightJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();

// crossJoin    
$users = Db::table('sizes')
            ->crossJoin('colors')
            ->get();

Union文

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

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

Where文

プロトタイプ

where($column, $operator = null, $value = null)

最初のパラメータは列名、2番目のパラメータは任意のデータベースシステムがサポートする演算子、3番目はその列と比較する値です。

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

// 演算子が等号の場合は省略できるため、この式は前の式と同じ効果があります
$users = Db::table('users')->where('votes', 100)->get();

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

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

$users = Db::table('users')
                ->where('name', 'like', 'T%')
                ->get();

条件の配列を where 関数に渡すこともできます:

$users = Db::table('users')->where([
    ['status', '=', '1'],
    ['subscribed', '<>', '1'],
])->get();

orWhere メソッドと where メソッドは同じパラメータを受け取ります:

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

orWhere メソッドにクロージャを最初のパラメータとして渡すこともできます:

// SQL: select * from users where votes > 100 or (name = 'Abigail' and votes > 50)
$users = Db::table('users')
            ->where('votes', '>', 100)
            ->orWhere(function($query) {
                $query->where('name', 'Abigail')
                      ->where('votes', '>', 50);
            })
            ->get();

whereBetween / orWhereBetween メソッドはフィールド値が指定された2つの値の間にあるかどうかを確認します:

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

whereNotBetween / orWhereNotBetween メソッドはフィールド値が指定された2つの値の外にあるかどうかを確認します:

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

whereIn / whereNotIn / orWhereIn / orWhereNotIn メソッドはフィールドの値が指定された配列に存在するかどうかを確認します:

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

whereNull / whereNotNull / orWhereNull / orWhereNotNull メソッドは指定されたフィールドが NULL であるかどうかを確認します:

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

whereNotNull メソッドは指定されたフィールドが NULL でないかどうかを確認します:

$users = Db::table('users')
                    ->whereNotNull('updated_at')
                    ->get();

whereDate / whereMonth / whereDay / whereYear / whereTime メソッドはフィールド値と指定された日付を比較します:

$users = Db::table('users')
                ->whereDate('created_at', '2016-12-31')
                ->get();

whereColumn / orWhereColumn メソッドは、2つのフィールドの値が等しいかどうかを比較します:

$users = Db::table('users')
                ->whereColumn('first_name', 'last_name')
                ->get();

// 比較演算子を渡すこともできます
$users = Db::table('users')
                ->whereColumn('updated_at', '>', 'created_at')
                ->get();

// whereColumn メソッドも配列を渡すことができます
$users = Db::table('users')
                ->whereColumn([
                    ['first_name', '=', 'last_name'],
                    ['updated_at', '>', 'created_at'],
                ])->get();

パラメータのグループ化

// select * from users where name = 'John' and (votes > 100 or title = 'Admin')
$users = Db::table('users')
           ->where('name', '=', 'John')
           ->where(function ($query) {
               $query->where('votes', '>', 100)
                     ->orWhere('title', '=', 'Admin');
           })
           ->get();

whereExists

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

orderBy

$users = Db::table('users')
                ->orderBy('name', 'desc')
                ->get();

ランダムソート

$randomUser = Db::table('users')
                ->inRandomOrder()
                ->first();

ランダムソートはサーバーの性能に大きな影響を与えるため、使用しないことをお勧めします。

groupBy / having

$users = Db::table('users')
                ->groupBy('account_id')
                ->having('account_id', '>', 100)
                ->get();
// groupBy メソッドには複数のパラメータを渡すことができます
$users = Db::table('users')
                ->groupBy('first_name', 'status')
                ->having('account_id', '>', 100)
                ->get();

offset / limit

$users = Db::table('users')
                ->offset(10)
                ->limit(5)
                ->get();

挿入

1件の挿入

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

複数件の挿入

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

自動増分 ID

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

注意:PostgreSQLを使用する場合、insertGetId メソッドはデフォルトで id を自動増分フィールドの名前として扱います。他の「シーケンス」からIDを取得する場合は、フィールド名を第2パラメータとしてinsertGetId メソッドに渡すことができます。

更新

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

更新または挿入

既存のレコードを更新したり、マッチするレコードが存在しない場合は新たに作成したい場合があります:

Db::table('users')
    ->updateOrInsert(
        ['email' => 'john@example.com', 'name' => 'John'],
        ['votes' => '2']
    );

updateOrInsert メソッドはまず、第一引数のキーと値のペアを使ってデータベースレコードを検索し、レコードが存在する場合は第二引数の値を用いて更新します。レコードが見つからない場合は、新しいレコードを挿入します。この新しいレコードのデータは、二つの配列の集合体です。

自動増分 & 自動減少

これらのメソッドは、変更する列を指定するために少なくとも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']);

削除

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

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

テーブルを空にする必要がある場合、truncate メソッドを使用できます。これはすべての行を削除し、自動増分 ID をゼロにリセットします:

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

トランザクション

データベーストランザクションを参照してください。

悲観ロック

クエリビルダーには、 select 構文で「悲観的ロック」を実装するためのいくつかの関数が含まれています。クエリで「共有ロック」を実装するには、 sharedLock メソッドを使用します。共有ロックは選択されたデータ列が取引がコミットされるまで変更されるのを防ぎます:

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

または、 lockForUpdate メソッドを使用できます。「update」ロックを使用することで、行が他の共有ロックによって変更されたり選択されたりするのを回避します:

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

デバッグ

 dd または dump メソッドを使用してクエリ結果やSQL文を出力できます。 dd メソッドはデバッグ情報を表示し、その後リクエストの実行を停止します。 dump メソッドもデバッグ情報を表示しますが、リクエストの実行は停止しません:

Db::table('users')->where('votes', '>', 100)->dd();
Db::table('users')->where('votes', '>', 100)->dump();

注意
デバッグにはsymfony/var-dumperをインストールする必要があります。コマンドはcomposer require symfony/var-dumperです。