Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent sum of multiplied columns

I have a table named transactions in mysql database and I am going to use Laravel's Eloquent ORM (Laravel 5) to get sum of multiplied column (jumlah) and (harga), this what my table looks alike:

+----+----------+-------------+--------+---------+------------+---------------------+---------------------+
| id | order_id | nama_barang | jumlah | harga   | keterangan | created_at          | updated_at          |
+----+----------+-------------+--------+---------+------------+---------------------+---------------------+
|  4 |        3 | PS 4        |      2 | 4500000 | Hitam      | 2015-05-20 08:55:26 | 2015-05-20 08:56:14 |
+----+----------+-------------+--------+---------+------------+---------------------+---------------------+

And I want to get result something like this:

select sum(jumlah * harga) from transactions;
+---------------------+
| sum(jumlah * harga) |
+---------------------+
|             9000000 |
+---------------------+

How to do that with ORM Laravel, I tried this one, but it gives me 0:

$amount = Transaction::all()->sum('(jumlah * harga)');
like image 786
oentoro Avatar asked Nov 26 '22 22:11

oentoro


1 Answers

Try use this

$amount = Transaction::select(DB::raw('sum(jumlah * harga) as total'))->get();
like image 87
Imtiaz Pabel Avatar answered Dec 04 '22 02:12

Imtiaz Pabel