LoginSignup
38
35

More than 5 years have passed since last update.

laravelでDBレコードの存在チェック方法

Last updated at Posted at 2018-05-30

現プロジェクトでよく使うけど書いとかないと忘れそうなので備忘録メモ

環境

Laravel Framework 5.5

DBの存在チェック方法

Controller
DB::table(table_name)->where(column, $data)->exists();

戻り値:bool

とても簡単。

sql直書きしてDBの存在チェック

ほとんどないけどたまに「date_fomat()」使って日付を文字列にして比較したい!ということがあった。

Controller
$ym = '201805';
DB::table(table_name)->whereRaw('date_format(date_column, "%Y%m") = ?', [$ym])->exists();

公式読めばわかるけど第3引数にバインド値の配列が指定できるよ。
参考:Laravel 5.5 データベース:クエリビルダ

ちなみにつなげて書く方法でもできる。推奨しない。

Controller
$ym = '201805';
DB::table(table_name)->whereRaw('date_format(date_column, "%Y%m") = ' . $ym)->exists();

余談

Controller
DB::table(table_name)->where(DB::raw('date_format(date_column, "%Y%m") = 201805'))->exists();

sql直書きするときDB::raw()を使って書いてたけど実行するとなぜかis nullがついてくる。
調べてみたけど全然わからなかったので誰かご存知でしたら教えてください。

38
35
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
35