LoginSignup
22
21

More than 5 years have passed since last update.

LaravelのEloquentで複数の項目のsumをする

Posted at

なんでこの記事を書いたか

pointsテーブル

+--------+----------------+
|id      |  point|    used|
+-------------------------+
|       1|     10|      10|
+-------------------------+
|       2|     20|      11|
+-------------------------+
|       3|     30|      12|
+-------------------------+
|       4|     40|      13|
+-------------------------+

このようなテーブルがある。
pointは総ポイント、usedは使用済ポイント
全ユーザの所持ポイントと使用済みポイントの合計を知りたい時

$point_sum = Point::sum("point");
$used_sum = Point::sum("used");

のように、2行で書く必要がある。
この場合、SQLクエリは2回流れる(はず)

できれば1度のSQLクエリで結果を得たい。

他の問題点

  • groupByできないよね
  • where句をつけたら条件の数だけコードが増えるよね

解決方法 ?

Point::select(DB::raw("sum(point) as total_point,sum(used) as total_used"))->get();

このようにする

また

Point::select(DB::raw("sum(point) as total_point,sum(used) as total_used"))->where("point","=","used")->get();

のように、where句をつけるとができ、ポイントを使い切っていない人のみの集計などができる

Point::select(DB::raw("type,sum(point) as total_point,sum(used) as total_used"))->groupBy("type")->get();

※type列をテーブルに追加したと仮定して
typeごとの集計なども得られる

問題点

DB::raw()になるので、中の式が固定になる(動的に文字列結合とかは怖い)

他にいい方法があれば教えてください

22
21
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
22
21