Mysql 如何将自定义查询转换为laravel 5?

Mysql 如何将自定义查询转换为laravel 5?,mysql,laravel,eloquent,query-builder,Mysql,Laravel,Eloquent,Query Builder,我正在从交易表中获取订单id、创建日期、交易金额。我得到了一些订单id、创建日期和交易金额的记录。现在我想要交易金额的总和列。我尝试直接在db上执行以下查询,但无法在laravel中编写相同的查询 select sum(transaction_amount) from ( select order_id, max(created_at), transaction_amount from transactions WHERE user_id =100 AND accounting_type = "

我正在从交易表中获取订单id、创建日期、交易金额。我得到了一些订单id、创建日期和交易金额的记录。现在我想要交易金额的总和列。我尝试直接在db上执行以下查询,但无法在laravel中编写相同的查询

select sum(transaction_amount) from (
select order_id, max(created_at), transaction_amount
from transactions
WHERE user_id =100 AND accounting_type = "Debit"
group by order_id
limit 500 ) as transactions
我试过这种方法,但仍然不起作用

$sql = "select sum(transaction_amount) from 
                ('select order_id, max(created_at), transaction_amount
                from transactions
                WHERE user_id =100 
                group by order_id
                limit 500') as transactions";
        $result = \DB::select( \DB::raw($sql));

我认为
$sql
变量必须只包含
from
中的子查询

Laravel QueryBuilder的
table()
方法是SQL中
FROM
语句的“等价物”,您就是在这里放置子查询的

试一试

相反,如果您想使用您尝试使用的
select()
方法进行并行:

$result = \DB::table(\DB::raw($sql))->select(\DB::raw('sum(transaction_amount) as sum'))->get();

首先,让我们对您的查询进行细分: 主查询

SELECT
SUM( transaction_amount )
FROM
    (...) AS transactions
这只是用于总结。以及您的子查询:

        SELECT
            order_id,
            MAX( created_at ),
            transaction_amount
        FROM
            transactions
        WHERE
            user_id = 100
            AND accounting_type = "Debit"
        GROUP BY
            order_id LIMIT 500
对于子查询,Laravel查询生成器应为:

use DB;

$result = DB::table('table')
->select(DB::raw("order_id, MAX(created_at), transaction_amount"))
->where("user_id", "=", 100)
->where("accounting_type", "=", "Debit")
->groupBy("order_id")
->limit(500)
->get(); // this will return Laravel Collection (Illuminate\Support\Collection)
Laravel集合具有
sum
方法,因此您可以调用它

$result->sum('transaction_amount');

有关更多信息,请阅读和Laravel文档。

您的
用户id
列在哪里?如果在事务表中,那么您没有选择,那么如何将其与where一起使用呢?
DB:raw()
应该可以。到底是什么不起作用?你有错误吗?我想知道
行中的
用户id
在哪里(“用户id”,“=”,100)
可以工作?它将从哪里来?我认为
DB::table()
必须是
DB::table('transactions')
才能工作。SQL的
where
子句中的列并不意味着必须存在于
SELECT
子句中,请尝试一下。但可能是您在使用
GROUP BY
时的意思。
groupby
cluse中使用的列应存在于
SELECT
子句中。CMIIW
$result->sum('transaction_amount');