如何使用相同的查询,只需更改where
语句,如下所示:
$query = Transaction::ofBranch($this->merchant_id)->where(DB::raw('MONTH(created_at)'), Carbon::now()->subMonths($value)->format('m'));
$count = $query->count();
$total_paid = $query->where('status',1)->sum('amount');
$total_unpaid = $query->where('status',0)->sum('amount');
我得到了除$total_unpaid
之外的所有结果。
当我检查时,查询似乎已被total_paid
取代。所以$total_unpaid
没有结果。
我有什么方法可以让它更有效率并且不会重复基本查询?
由于
答案 0 :(得分:1)
$query = Transaction::ofBranch($this->merchant_id)->where(DB::raw('MONTH(created_at)'), Carbon::now()->subMonths($value)->format('m'));
解决方案是使用克隆,当您扩展此查询时,原始查询将保持相同且不会更改。
E.g
$clone = clone $query;
您可以使用此代替$query
使用此
$count = $clone ->count();
不是这个:
$count = $query->count();
其他人会像
$total_paid = $clone->where('status',1)->sum('amount');
$total_unpaid = $clone->where('status',0)->sum('amount');
答案 1 :(得分:0)
您可以尝试:
$query = Transaction::ofBranch($this->merchant_id)->where(DB::raw('MONTH(created_at)'), Carbon::now()->subMonths($value)->format('m'));
$count = $query->count();
$total_paid = $query->where('status',1)->sum('amount');
$total_unpaid = $query->orWhere('status',0)->sum('amount');