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

monstajamss's avatar

Writing SQL Query in Laravel Eloquent Way

I have this SQL Query

"SELECT
		MIN(IF(c.description IS NOT NULL, c.description, yec.cat_desc)) AS cat_desc,
		SUM(yec.{$time_period->yec_kwh_used}) AS kwh_used,
		SUM(yec.{$time_period->yec_cost}) AS cost,
		yec.category_id
	FROM `{$time_period->yec_table}` AS yec
	LEFT JOIN category AS c ON yec.category_id = c.id
	WHERE
		yec.category_id <> '$billing_category'
		AND yec.building_id = '$building->id'
		AND yec.category_id NOT IN (SELECT category_id FROM building_category_settings WHERE building_id = '$building->id' AND hide_from_electricity_widget = 1)
	GROUP BY category_id
	ORDER BY kwh_used DESC
";

But i am trying to write in laravel way i tried doing this

$electCategory = $this->electricityConnections->select(\DB::raw("MIN(IF(c.description IS NOT NULL, c.description, yec_cat_desc)) AS cat_desc", 
        ('SUM(yec.kwh_used) as khw_used'), ('SUM(yec.cost) as cost'), 'yec.category_id' ))
        ->leftJoin('category as c')
        ->first();

But it is not displaying what i want i am getting this error Too few arguments to function Illuminate\\Database\\Query\\Builder::leftJoin()

I have a your_electricity_yesterday_category table that has cost , khw_used, cat_desc andcategory_id as column.

Any help would be appreciated

0 likes
2 replies
Sinnbeck's avatar

Left join needs to know what to join on, just as your original query

->leftJoin('category as c', 'yec.category_id', 'c.id')
monstajamss's avatar

@Sinnbeck I wanted to break everything down to better understand it so i started by doing this

 $electCategory = $this->electricityConnections->select(\DB::raw('MIN(IF(cat_desc IS NOT NULL) as cat_desc)'), (\DB::raw('SUM(kwh_used) as kwh_used')), (\DB::raw('SUM(cost) as cost')))->first();
        

but i got this error "message": "SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') as cat_desc), SUM(kwh_used) as kwh_used, SUM(cost) as cost from `your_electric' at line 1 (SQL: select MIN(IF(cat_desc IS NOT NULL) as cat_desc), SUM(kwh_used) as kwh_used, SUM(cost) as cost from `your_electricity_yesterday_category` limit 1)",

Any idea what i am doing wrong?

Please or to participate in this conversation.