需要关于如何构建Laravel数据库查询的指导



在Laravel 6.18中,我试图弄清楚如何重新创建以下Postgres查询。

with data as (
select date_trunc('month', purchase_date) as x_month,  date_trunc('year', purchase_date) AS x_year,
sum (retail_value) AS "retail_value_sum" 
from coins 
where user_email = 'user@email.com' and sold = 0
group by x_month, x_year
order by x_month asc, x_year asc
)
select x_month, x_year, sum (retail_value_sum) over (order by x_month asc, x_year asc rows between unbounded preceding and current row)
from data

我知道如何构建查询的主要部分

$value_of_all_purchases_not_sold = DB::table('coins')
->select(DB::raw('date_trunc('month', purchase_date) AS x_month, date_trunc('year', purchase_date) AS x_year, sum(retail_value) as purchase_price_sum'))
->where('user_email', '=', auth()->user()->email)
->where('sold', '=', 0)
->groupBy('x_month', 'x_year')
->orderBy('x_month', 'asc')
->orderBy('x_year', 'asc')
->get();

但是,如何构建数据为(的,第二个选择

我需要数据是累积的,我宁愿在DB中而不是在PHP中进行计算。

Laravel没有用于common table expression的内置方法。你可以使用这样的第三方软件包——它有很好的文档。如果您不想使用外部库,那么您需要使用具有绑定(如(的查询生成器的select方法
$results = DB::select('your-query', ['your', 'bindings']);
return Coin::hydrate($results); // if you want them as collection of Coin instance.

最新更新