php Laravel 查询生成器 - sum() 方法问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30424949/
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
Laravel Query Builder - sum() method issue
提问by burn15
Ehi there, I'm new in laravel and I have some issues with laravel query builder. The query I would like to build is this one:
嗨,我是 laravel 的新手,我在使用 laravel 查询构建器时遇到了一些问题。我想构建的查询是这样的:
SELECT SUM(transactions.amount)
FROM transactions
JOIN categories
ON transactions.category_id == categories.id
WHERE categories.kind == "1"
I tried building this but isn't working and I can't figure out where I am wrong.
我尝试构建它但不起作用,我无法弄清楚我错在哪里。
$purchases = DB::table('transactions')->sum('transactions.amount')
->join('categories', 'transactions.category_id', '=', 'categories.id')
->where('categories.kind', '=', 1)
->select('transactions.amount')
->get();
I would like to get all the transactions that have the attribute "kind" equal to 1 and save it in a variable. Here's the db structure:
我想获取属性“kind”等于 1 的所有交易并将其保存在一个变量中。这是数据库结构:
transactions(id, name, amount, category_id)
categories(id, name, kind)
交易(id,名称,金额,category_id)
类别(ID,名称,种类)
回答by Limon Monte
You don't need to use select()
or get()
when using the aggregate method as sum
:
您不需要使用select()
或get()
当使用聚合方法时sum
:
$purchases = DB::table('transactions')
->join('categories', 'transactions.category_id', '=', 'categories.id')
->where('categories.kind', '=', 1)
->sum('transactions.amount');
回答by Yogesh Mistry
If one needs to select SUM
of a column along with a normal selection of other columns, you can sum select that column using DB::raw
method:
如果需要选择SUM
一列以及其他列的正常选择,您可以使用DB::raw
方法sum 选择该列:
DB::table('table_name')
->select('column_str_1', 'column_str_2', DB::raw('SUM(column_int_1) AS sum_of_1'))
->get();
回答by Rasheduzzaman
Aggregates methods of query builder are:
查询构建器的聚合方法是:
1) max()
2) min()
3) sum()
4) avg()
5) count()
You can use like,
你可以使用像,
$purchases = DB::table('transactions')
->join('categories', 'transactions.category_id', '=', 'categories.id')
->where('categories.kind', '=', 1)
->sum('transactions.amount');