Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

monstajamss's avatar

Change Vanilla SQL Query to Laravel

I have this query in my Vanilla PHP and SQL

I do i write this statement in laravel?

$sum_data = App::sql()->query_row("SELECT SUM({$time_period->yec_kwh_used}) AS kwh_used, SUM({$time_period->yec_cost}) AS cost FROM `{$time_period->yec_table}` WHERE category_id = ".sample::CATEGORY_BILLING." AND building_id = $building->id");
		$total_kwh = $sum_data ? $sum_data->kwh_used : 0;
		$total_cost = $sum_data ? $sum_data->cost : 0;
0 likes
3 replies
Sinnbeck's avatar

Something like this. Might need some tweaking. :)

\DB::table($time_period->yec_table)
->select(\DB::raw('SUM(?) as kwh_used', [$time_period->yec_kwh_used]), \DB::raw('SUM(?) as yec_cost', [$time_period->yec_cost])
->where('category_id', Eticom::CATEGORY_BILLING)
->where('building_id', $building->id)
->first();
monstajamss's avatar

@Sinnbeck I have a column of kwh_used and column of cost

How can i just write Query to get the cost where category = 11 and building id = 52?

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@monstajamss So it should just be like this?

\DB::table($time_period->yec_table)
->select(\DB::raw('SUM(kwh_used) as kwh_used'), \DB::raw('SUM(yec_cost) as yec_cost'])
->where('category_id', 11)
->where('building_id', 52)
->first();

Please or to participate in this conversation.