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

How to convert custom query to laravel 5?

我正在从事务 table 中获取 order_id、created_at 日期、transaction_amount。我得到了一些带有 order_id、created_at 日期和 transaction_amount 的记录。现在我想要 transaction_amount 列的总和。我尝试直接在 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.

的子查询

LaravelQueryBuilder的table()方法是SQL中FROM语句的“等价”,它在这里放置子查询。

尝试

$sql = 'select order_id, max(created_at), transaction_amount
            from transactions
            WHERE user_id =100 
            group by order_id
            limit 500';

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

相反,如果您想要与您尝试使用的 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');

有关详细信息,请阅读 this and this Laravel 文档。