【发布时间】:2020-08-26 09:13:00
【问题描述】:
我有许多必须重复的查询,因为它们取决于通过 Select (Today, Month & Year) 获得的过滤器的选择,该过滤器在上面指定的范围内显示相应的信息:当前日期、当前月份和当前年份。
代码如下:
if ($filterDashboardMerchant == 'month'){
// Total Revenue || Month
$totalRevenue = AffiliateOrder::join('affiliates', 'affiliates.id', '=', 'affiliates_orders.affiliate_id')
->whereMonth('order_date', Carbon::now()->month)
->select(DB::raw('sum(total) as orders_total'))
->where('affiliates.merchant_id', $merchant->merchant_id)
->get();
}
else{
if($filterDashboardMerchant == 'year'){
// Total Revenue || Year
$totalRevenue = AffiliateOrder::join('affiliates', 'affiliates.id', '=', 'affiliates_orders.affiliate_id')
->whereYear('order_date', Carbon::now()->year)
->select(DB::raw('sum(total) as orders_total'))
->where('affiliates.merchant_id', $merchant->merchant_id)
->get();
else{
// Total Revenue || Today
$totalRevenue = AffiliateOrder::join('affiliates', 'affiliates.id', '=', 'affiliates_orders.affiliate_id')
->whereDay('order_date', Carbon::now()->day)
->select(DB::raw('sum(total) as orders_total'))
->where('affiliates.merchant_id', $merchant->merchant_id)
->get();
}
}
假设所有查询代码都是相同的,其中只有 3 个条件不同:
->whereMonth('order_date', Carbon::now()->month)
->whereYear('order_date', Carbon::now()->year)
->whereDay('order_date', Carbon::now()->day)
如何在相同的代码 sn-p 中仅更改该条件,这取决于筛选到它们的 Select 中的选择?
这对我有很大帮助,因为这还不到我开发的 5%,它会为我节省大量代码。
【问题讨论】:
-
我的回答对您的问题有帮助吗?否则我很高兴尝试修复它:)
标签: sql laravel eloquent laravel-query-builder