DBファサードの使い方|Laravel

LaravelのコントローラではDBファサードを使用してデータベース操作が行えます。
本記事では基本的なデータベース操作についてのみ説明します。

データの取得

SELECT関係は以下のようにします。
reportsテーブルのstatusカラムの値が1以上のレコードを取得する例。

select()

$reports = DB::select('select * from reports where status >= ?', [1]);

table() を使う

$reports = DB::table('reports')
                ->where('status', '>=', 1)
                ->get();
DB::selectの戻り値は配列になります。get()で取得した戻り値はIlluminate\Support\Collectionクラスです。

条件指定のサンプル

where()orWhere()を使用した条件指定のサンプルです。

// 条件A かつ 条件B
DB::table('reports')
        ->where('status', '>=', 1) // 条件A
        ->where('status', '<', 10) // 条件B
        ->get();

// 条件A または 条件B
DB::table('reports')
        ->where('id', '=', $id) // 条件A
        ->orWhere('name', '<>', '') // 条件B
        ->get();

// 条件A かつ (条件B または 条件C)
DB::table('reports')
        ->where('id', '=', $id) // 条件A
        ->where(function ($query) {
            $query->orWhere('name', '<>', '') // 条件B
                  ->orWhere('detail', '<>', ''); // 条件C
        })
        ->get();

値の一致判定する場合、第2引数に値を記述する方法も可能です。下記はそれぞれ同じ意味になります。

->where('id', '=', $id)
->where('id', $id)

並べ替え

ORDER BY句は以下のように指定します。第1引数がカラム名です。

->orderBy('modified', 'ASC')

データベースの更新

update()

レコードを更新します。戻り値は更新件数です。

$result = DB::table('reports')
                ->where('id', '=', $id)
                ->update(['status' => 0]);

insert()

レコードを追加します。戻り値は成否の真偽値です。

$result = DB::table('reports')
                ->insert(['id' => $id, 'status' => 1]);

delete()

レコードを削除します。戻り値は削除件数です。

$count = DB::table('reports')
            ->where('status', 99)
            ->delete();
このエントリーをはてなブックマークに追加
にほんブログ村 IT技術ブログへ

スポンサードリンク

関連コンテンツ

コメント

メールアドレスが公開されることはありません。 が付いている欄は必須項目です