LoginSignup
12
8

More than 3 years have passed since last update.

【Laravel5.6】whereColumnで2つのカラムの日付比較をする

Last updated at Posted at 2018-07-28

Laravel EloquentクエリービルダーのwhereColumn()メソッドを使用して、
2つのカラムにある日付を比較して、最終的な結果をgetで取得します。

テーブル構造例

下記のようなテーブルがあるとする。

id name action_at login_at
1 A 2018-07-27 12:00:00 2018-07-27 11:00:00
2 B 2018-07-27 11:00:00 2018-07-27 12:00:00
3 C 2018-07-27 12:00:00 null
4 D null 2018-07-27 12:00:00

やりたい事

日付日時がlogin_atよりもaction_atの方が遅いデータを取得したい。
この場合、取得したい期待値データは、id1のデータになる。

実現方法

whereColumn()メソッド は、同値判定だけでなく、比較演算子も使えます。
今回は下記の様な形でコードを記述します。

$users = DB::table('users')
                ->whereColumn('action_at', '>', 'login_at')
                ->get();

すると

Collection {#293 ▼
  #items: array:1 [▼
    0 => User {#289 ▼
      #fillable: array:2 [▶]
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      .
      .
      .  
      #original: array:3 [▼
        "id" => 1
        "action_at" => "2018-07-27 12:00:00"
        "login_at" => "2018-07-27 11:00:00"
      ]
      .
      .
      .     
    }
  ]
}

id1のレコードを取得できます。

SQL

ここで、Laravelで実行されたSQLを確認してみると、

.
.
.

use DB;

.
.
.
// 確認したいSQLの前に追記
DB::enableQueryLog();
$users = DB::table('users')
                ->whereColumn('action_at', '>' 'login_at')
                ->get();
// dumpする
dd(DB::getQueryLog());

すると

array:1 [▼
  0 => array:3 [▼
    "query" => "select * from `matchings` where `action_at` > `login_at`"
    "bindings" => []
    "time" => 2.81
  ]
]

という出力結果になります。

whereColumn()メソッドの使い方

2つのカラムが同値である確認をする。


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

比較演算子を指定する。


$users = DB::table('users')
                ->whereColumn('updated_at', '>', 'created_at')
                ->get();

配列により複数の条件を渡すことができ、条件はandで繋ぐ事が可能。


$users = DB::table('users')
                ->whereColumn([
                    ['first_name', '=', 'last_name'],
                    ['updated_at', '>', 'created_at']
                ])->get();

参考

Laravel 5.6 データベース:クエリビルダ
https://readouble.com/laravel/5.3/ja/queries.html

12
8
2

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
12
8