LoginSignup
1
2

More than 3 years have passed since last update.

Laravel 1対多のリレーション先の項目の集計値(最小値, 最大値, 平均値, 合計値 など)で親テーブルを並べ替えたい

Last updated at Posted at 2020-06-30

テーブルの例

たとえば、商品基本情報と詳細が1対多の関係で、データベースを構成したとします。
一覧表示する時に、価格順で並び替えたい時はどんな感じにクエリビルダーを使えばいいか、いろいろ試してこれかなぁというのを投降します。

【商品情報テーブル (products)】
id 商品ID
name 商品名

【商品詳細テーブル (detail)】
id 商品詳細ID
productID 商品詳細ID
size サイズ
price 価格
visible 表示・非表示

コードの例

$aggregates = DB::table('detail')
    ->select('productID',
    DB::raw('MIN(price) as min_price'),
    DB::raw('MAX(price) as max_price')
)
    ->where('visible', 1)
    ->groupBy('itemID');

$db = DB::table('products')
    ->joinSub($aggregates, 'aggregates', function ($join) {
        $join->on('products.id', '=', 'aggregates. productID');
    })
    ->orderBy('min_price01', 'desc')
    ->get();

これなら、並び替えできます。ここ参考にしました。
https://readouble.com/laravel/6.x/ja/queries.html
最初は、joinでリレーションを作って、groupByでまとめ、価格の最大・最小をselectに入れて、を並び替えてみようとしたのが、できなかったので、こうなりました。

もっと上手な書き方があれば、こんな方法はどうだい?ってコメントいただけると、ありがたいです。
よろしくお願いいたします。

1
2
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
1
2