Laravel查询生成器-sum()方法问题 [英] Laravel Query Builder - sum() method issue

查看:69
本文介绍了Laravel查询生成器-sum()方法问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是laravel的新手,而laravel查询生成器存在一些问题.我想建立的查询就是这个:

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:

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

我想获取所有具有"kind"属性的交易.等于1并将其保存在变量中.这是数据库结构:

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:

交易( id ,名称,金额, category_id )

类别( id ,名称,种类)

推荐答案

使用聚合方法时,无需使用 select() get() sum :

You don't need to use select() or get() when using the aggregate method as sum:

$purchases = DB::table('transactions')
    ->join('categories', 'transactions.category_id', '=', 'categories.id')
    ->where('categories.kind', '=', 1)
    ->sum('transactions.amount');

了解更多: http://laravel.com/docs/5.0/queries#aggregates

这篇关于Laravel查询生成器-sum()方法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆