dimanche 6 janvier 2019

Laravel Select count with groupBy

I trying to get the count of batch in gift_code table grouping by campaign_id and batch. The gift_code table is joined to campaign table by campaign_id.

Here is some sample data for campaign table.

--------------+--------------
|campaign_id  | name        |
--------------+--------------
| 1           | abc         |
--------------+--------------
| 2           | xyz         |
--------------+--------------

Below is some sample data for gift_code table.

--------------+------------------------+--------------+
|gift_code_id | campaign_id | batch    | unique_code  |
--------------+-------------+----------+---------------
| 1           | 1           |    1     | zxc23        |
--------------+-------------+----------+--------------+
| 2           | 1           |    2     | rtc26        |
--------------+-------------+----------++-------------+
| 1           | 2           |    1     | zxc23        |
--------------+-------------+----------+--------------+
| 2           | 2           |    2     | rtc26        |
--------------+-------------+----------++-------------+
 $campaign = DB::table('campaign')
                    ->select('campaign.*', DB::raw('count(gift_code.batch) as batch_count')->groupBy('gift_code.campaign_id')->groupBy('gift_code.batch'))
                    ->leftjoin('gift_code', 'campaign.campaign_id', '=', 'gift_code.campaign_id')
                    ->get();



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2AtZ6on
via IFTTT

Aucun commentaire:

Enregistrer un commentaire