我有许多必须重复的查询,因为它们取决于通过Select (Today,Month & Year)获得的过滤器的选择,它显示了上面指定的范围内的相应信息: Current Day、Current Month和Year Current。
代码如下:
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)如何才能在相同代码片段中更改条件,这取决于对它们进行筛选的Select中的选择?
这将对我有很大的帮助,因为这只是我开发的不到5%,它将节省我大量的代码。
发布于 2020-05-11 07:15:13
Laravel有一个when()查询方法,它只在条件为真时执行给定的回调。Documentation。
AffiliateOrder::join('affiliates', 'affiliates.id', '=', 'affiliates_orders.affiliate_id')
->when($filterDashboardMerchant === 'day', function ($query) {
$query->whereDay('order_date', Carbon::now()->day);
})
->when($filterDashboardMerchant === 'month', function ($query) {
$query->whereMonth('order_date', Carbon::now()->month);
})
->when($filterDashboardMerchant === 'year', function ($query) {
$query->whereYear('order_date', Carbon::now()->year);
})
->select(DB::raw('sum(total) as orders_total'))
->where('affiliates.merchant_id', $merchant->merchant_id)
->get();要使用更简洁的方法作用域,请在AffiliateOrder.php类中添加作用域。
public function scopeFilterAffiliates($query, $filter) {
$query->join('affiliates', 'affiliates.id', '=', 'affiliates_orders.affiliate_id')
->when($filter === 'day', function ($query) {
$query->whereDay('order_date', Carbon::now()->day);
})
->when($filter === 'month', function ($query) {
$query->whereMonth('order_date', Carbon::now()->month);
})
->when($filter === 'year', function ($query) {
$query->whereYear('order_date', Carbon::now()->year);
})
->select(DB::raw('sum(total) as orders_total'))
->where('affiliates.merchant_id', $merchant->merchant_id);
}现在你可以像这样使用作用域了。
AffiliateOrder::filterAffiliates($filterDashboardMerchant)
->get();https://stackoverflow.com/questions/61719367
复制相似问题