Laravel Eloquent乘以列的总和

时间:2015-05-20 09:16:39

标签: php mysql laravel eloquent

我在mysql数据库中有一个名为transactions的表,我将使用Laravel的Eloquent ORM(Laravel 5)来获得乘法列(jumlah)和(harga)的总和,这就是我的表看起来很相似:

+----+----------+-------------+--------+---------+------------+---------------------+---------------------+
| 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 |
+----+----------+-------------+--------+---------+------------+---------------------+---------------------+

我希望得到这样的结果:

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

如何使用ORM Laravel,我试过这个,但它给了我0

$amount = Transaction::all()->sum('(jumlah * harga)');

7 个答案:

答案 0 :(得分:8)

尝试使用此

$amount = Transaction::select(DB::raw('sum(jumlah * harga) as total'))->get();

答案 1 :(得分:2)

雄辩的风格如下:

$amount = Transaction::all()->sum(function($t){ 
    return $t->jumlah * $t->harga; 
});

答案 2 :(得分:0)

您必须在此处使用DB::raw方法:

Transaction::all()->select(DB::raw('sum(jumlah * harga) AS sum_of_jumlah_harga'))

答案 3 :(得分:0)

  $particulars =DB::table('particulars as A')
        ->leftjoin('reqs as B', function ($join) {
            $join->on('A.particular_id', '=', 'B.particular_id');
        })
        ->whereBetween('B.date_issued', [$start_date, $end_date])
        ->select('A.item_name','A.unit','A.price','B.quantity_issued',DB::raw('sum(A.price*B.quantity_issued) as total_cost'))
        ->groupBy('A.particular_id')
        ->get();

使用放置表名

来使用类似的东西

答案 4 :(得分:0)

$amount = Transaction::sum(\DB::raw('jumla * harga'));

这比较雄辩地完成。简而言之,它很快。

另一个例子:

$order_total = $order->products()->sum(\DB::raw('order_product.price * order_product.quantity'));

答案 5 :(得分:0)

你可以使用 Laravel 访问器

<块引用>

https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor

public function getTotalAttribute()
{
    return $this->all()->sum(function($transaction){
        return $transaction->jumlah * $transaction->harga; 
    });
}
At the top of your Order model put
protected $appends = ['total'];
you can get total like this (new Transaction)->total;

答案 6 :(得分:0)

答案分两步

首先,得到总和

$transaction = Transaction::select(\DB::raw('SUM(jumlah) as jumlak, SUM(harga) as harga'))
->first()

然后做乘法

$amount = $transaction->jumlah * $transaction->harga;