user7956165
user7956165

Reputation:

Query with sum many columns from same table with laravel query

This seems very easy query but can't translate it into laravel query. I have table orders there are two columns total_usd and total_gbp. I want to sum each column to get total of usd and total of gbp on the page.

This query is working in phpmyadmin and I got correct result

SELECT sum(order_total_usd) as usd, sum(order_total_gbp) as gbp FROM `orders`

In laravel I've tried this

$sumOrders = Order::select('sum(order_total_gbp) as gbp, sum(order_total_usd) as usd');

when I dd($sumOrders) I've one really huge output which almost cause browser to freeze. Where is my mistake here?

Upvotes: 1

Views: 955

Answers (3)

alex t
alex t

Reputation: 861

Except for one missed word, your code is OK. Add "Raw" after "select" as shown:

$sumOrders = 
Order::selectRaw(
    'sum(order_total_gbp) as gbp, 
    sum(order_total_usd) as usd'
);

Just replace "Order::select(...)" with Order::selectRaw(...).

Have a great day!

Upvotes: 0

vijaykumar
vijaykumar

Reputation: 4806

You can use selectRaw

$sumOrders = Order::selectRaw('sum(order_total_gbp) as gbp, sum(order_total_usd) as usd');

Upvotes: 0

Yashvantsinh Zala
Yashvantsinh Zala

Reputation: 531

You can try something like this

$sumOrders = Order::select( \DB::raw("sum(order_total_gbp) as gbp"),  \DB::raw("sum(order_total_usd) as usd"))->get();

Upvotes: 1

Related Questions