Laravel Eloquent 乘法列的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30345350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:35:22  来源:igfitidea点击:

Laravel Eloquent sum of multiplied columns

phpmysqllaraveleloquent

提问by oentoro

I have a table named transactionsin 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:

我有一个transactions在 mysql 数据库中命名的表,我将使用 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 |
+----+----------+-------------+--------+---------+------------+---------------------+---------------------+

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:

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

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

回答by Imtiaz Pabel

Try use this

尝试使用这个

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

回答by bono

Eloquent style is as below:

Eloquent 风格如下:

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

回答by doncadavona

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

This is more Eloquently done. In short, it's fast.

这是更雄辩地完成。简而言之,它很快。

Another example:

另一个例子:

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

回答by fetty

  $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();

use something like this by using placing your table name

通过放置您的表名来使用这样的东西

回答by P??

You have to use the DB::rawmethod here:

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

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