having is used where aggregate functions are within the where clause
xxxxxxxxxx
$orders = DB::table('orders')
->select('department', DB::raw('SUM(price) as total_sales'))
->groupBy('department')
->havingRaw('SUM(price) > ?', [2500])
->get();
xxxxxxxxxx
User::query()
->where('users.ban', '!=', 1)
->where('users.rights', '=', 1)
->leftJoin('users as referal', 'users.id', '=', 'referal.ref_id')
->whereNotNull('referal.id')
->select([
'users.id',
'users.name',
'users.telegram_id',
DB::raw('count(referal.id) as total_referal'),
DB::raw("(SELECT COUNT(ac_r.id) FROM users as ac_r WHERE ac_r.ref_id=users.id AND ac_r.ref_bonus = 1) as active_referal"),
DB::raw("(SELECT COUNT(ac_r.id) FROM users as ac_r WHERE ac_r.ref_id=users.id AND ac_r.ref_bonus != 1) as no_active_referal"),
DB::raw("((SELECT COUNT(ac_r.id) FROM users as ac_r WHERE ac_r.ref_id=users.id AND ac_r.ref_bonus = 1) * ".User::REFERAL_BONUS.") as total_money_referal"),
])
->groupBy('users.id')
->orderByDesc('total_referal')->paginate(100);
xxxxxxxxxx
// whereRaw
$orders = DB::table('orders')
->whereRaw('price > IF(state = "TX", ?, 100)', [200])
->get();
// havingRaw
Product::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get();
// orderByRaw
User::where('created_at', '>', '2016-01-01')
->orderByRaw('(updated_at - created_at) desc')
->get();
xxxxxxxxxx
$totalUsers = MyInventoryModel::selectRaw('pos_inventory.id as pos_inventory_id,pos_products.*,pos_products.product_name as product_name,pos_inventory.reorder_point,pos_inventory.reorder_qty,pos_inventory.current_stock,
pos_inventory.variant_id,pos_products.product_sku,pos_product_variants.combination_names,pos_product_variants.sku,pos_outlets.*,pos_roles.*')
->leftJoin('pos_products', 'pos_inventory.product_id', '=', 'pos_products.id')
->leftJoin('pos_product_variants', 'pos_inventory.product_id', '=', 'pos_product_variants.id')
->leftjoin('pos_outlets', 'pos_inventory.outlet_id', '=', 'pos_outlets.id')
->leftjoin('pos_roles', 'pos_outlets.store_id', '=', 'pos_roles.store_id')
->where('outlet_id', $item->outlet_id)
->groupBy('pos_inventory.product_id')
->get();