Laravelメモ

すぐ忘れちゃって探すのに無駄時間使ってるのをここにメモ。

1. クエリービルダー

1-1. 実行されるSQLやバインドする変数を確認する

//get()とかupdate()とか途中経過を保存しとくと便利
$DB = DB::table('hoge')->where('fuga_date', '<', DB::raw("(NOW() - INTERVAL '10 days')"));

//sqlが見れる
dump($DB->getSql());  //select * from hoge where fuga_date < (NOW() - INTERVAL '10 days')

//バインド変数が見れる
dump($DB->getBindings()); //[] ... 今回は何もバインドしてない

//実行
$ret = $DB->get();

//全部表示
dump([$DB->getSql(), $DB->getBindings(), $DB->get()]);

1-2. DB::raw()を使う

//SELECT col, count(*) AS count  FROM table GROUP BY col;
$result = DB::table('table')
    ->select('col', DB::raw('count(*) AS count'))
    ->groupBy('col')
    ->get();