Created
June 26, 2019 16:51
-
-
Save patrickmaciel/6020979388b8fd9edf6ae6768b4157e1 to your computer and use it in GitHub Desktop.
Query Builder with join group and count raw
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$stores = DB::table('stores as s') | |
->leftJoin('products as p', 'p.store_id', '=', 's.id') | |
->leftJoin('coupons as c', 'c.product_id', '=', 'p.id') | |
->leftJoin('coupon_user as cp', function($join) { | |
$join->on('cp.coupon_id', '=', 'c.id') | |
->on('cp.used', '=', DB::raw(1)); | |
}) | |
->leftJoin('coupons as c2', 'c2.product_id', '=', 'p.id') | |
->leftJoin('coupon_user as cp2', function($join) { | |
$join->on('cp2.coupon_id', '=', 'c.id') | |
->on('cp2.used', '=', DB::raw(0)); | |
}) | |
->select('s.*', | |
DB::raw('COUNT(p.id) AS products'), | |
DB::raw('COUNT(c2.id) AS linked'), | |
DB::raw('COUNT(c.id) AS used')) | |
->groupBy('s.id', | |
's.name', | |
's.description', | |
's.logo', | |
's.cover', | |
's.created_at', | |
's.updated_at', | |
's.deleted_at') | |
->paginate(25); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment