###前提・実現したいこと
laravel5.5にて、下記のSQLをEloquentで書こうと考えました。
SQL
1SELECT 2 * 3FROM 4 `M_Unitprices` --単価マスタ 5 --対象日を見て、最も直近の単価マスターを取得したい 6 INNER JOIN ( 7 SELECT 8 MAX(TARGETDATE) AS TARGETDATE, 9 EMPLOYEECODE 10 FROM 11 `M_Unitprices` 12 WHERE 13 `targetDate` <= ? 14 GROUP BY 15 `employeeCode` 16 ) AS MU 17 ON `M_Unitprices`.`targetDate` = `MU`.`targetDate` 18 AND `M_Unitprices`.`employeeCode` = `MU`.`employeeCode`
このSQLをEloquentで実装した場合、私は下記の様にコードを書きました。
PHP
1 //サブクエリの内容を記述 2 $subQuery = DB::table('M_Unitprices')->select(DB::raw('max(targetDate) as targetDate,employeeCode')) 3 ->where('targetDate','<=',$workDate)->groupBy('employeeCode'); 4 //DB::rawにてサブクエリをSQL化 5 return M_Unitprice::join(DB::raw('('.$subQuery->toSql().') As MU') , 6 function($join) use ($subQuery) { 7 $join->on('M_Unitprices.targetDate', '=', 'MU.targetDate') 8 ->on('M_Unitprices.employeeCode', '=', 'MU.employeeCode') 9 ->addBinding($subQuery->getBindings(), 'join'); 10 })->get()
この記述により、欲しいレコードを抽出する事が出来たのですが、M_Unitprice::join(DB::raw('('.$subQuery->toSql().') As MU')
という書き方はコードをSQLを直で書いているのと同じ感覚になるので、邪道ではないかと悩んでいます。
他に上記のSQLをEloquentでうまく書く良いやり方をご存知の方がいたら教えて頂けると嬉しいです。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/11/07 05:09
2017/11/07 05:22