6

流暢なクエリビルダーを使用して、1 つのクエリで複数のフィールドの合計を取得できるかどうか疑問に思っています。

現在、イベントと出席者の 2 つのテーブルがあります。出席者はイベントに属し、total_raised と total_hours の 2 つのフィールドがあります。私がやりたいことは、すべてのイベントと、そのイベントに費やされた総調達額/総時間数を選択することです。今、私が単に SQL を使用していた場合、次の効果を得るために何かを行います。

 SELECT Event.id, sum(Attendees.total_raised), sum(Attendees.total_hours)
 FROM Events JOIN Attendees ON Events.id = Attendees.event_id 
 GROUP BY Event.id

ただし、流暢なクエリ ビルダーを使用して一度に複数の合計を取得する方法が見つからないようです。fluent を使用してやろうとしていることを行う方法はありますか、それとも生の SQL クエリにする必要がありますか?

4

4 に答える 4

7

sum()つまり、次を使用できます。

$q = DB::table('events')
       ->join('attendees', 'events.id', '=', 'attendees.event_id')
       ->sum('total_raised')
       ->sum('total_hours');

それでもうまくいかない場合は、次を試してください。

...

->get(
  array(
    'events.id',
    DB::raw('SUM(attendees.total_raised)'),
    DB::raw('SUM(attendees.total_hours)')
  )
);
于 2013-03-12T18:32:19.410 に答える
0

シモーンズの答えに基づいています。これは、基本的に 2 つのクエリを実行することで実行できます。

$query = DB::table('events')->join('attendees', 'events.id', '=', 'attendees.event_id');

$raised = $query->sum( 'total_raised' );

$hours = $query->sum( 'total_hours' );

状況によります。それが管理者/CMS側にある場合、私はこのソリューションに傾倒します。フロントエンドにある場合は、単一のクエリで実行する必要があります。これにより高速になります。内容によっては、大きな違いになる場合とそうでない場合があります。

$result = DB::table('events')->join('attendees', 'events.id', '=', 'attendees.event_id')
    ->get( array(
        DB::raw( 'SUM(attendees.total_raised) AS raised' ),
        DB::raw( 'SUM(attendees.total_hours) AS hours' ),
    ));
于 2013-03-12T19:11:26.160 に答える
0

私は自分のプロジェクトで同じことをしています。これが私が見つけた解決策です。私は Laravel 5.2 Eloquent を使用しています。ここに Eloquent ステートメントがあります。

私のプロジェクトで使用するこのステートメントは、必要に応じて変更してください。

$result = self::select("*", DB::raw('SUM(auction_amount) as total_auction_amount') , DB::raw('SUM(commission_amount) as total_commission_amount'), 
            DB::raw('SUM(deposit_amount) as total_deposit_amount'))
            ->groupBy('cp_user_id')
            ->get()
            ->toArray();

次のようなクエリに使用できるのと同じ方法

$result = self::select("*", DB::raw('SUM(auction_amount) as total_auction_amount') , DB::raw('SUM(Attendees.total_raised) as total_raised'), 
            DB::raw('SUM(Attendees.total_hours) as total_hours'))
            ->with('Attendees')
            ->groupBy('id')
            ->get()
            ->toArray();
于 2017-01-23T06:24:35.560 に答える