0

How can I using same query and just change the where statement like this:

$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');

I got all result except $total_unpaid.

When I check, it appears the query has been replaced by total_paid. So the $total_unpaid has no results.

Is there any way I can make it work or any idea to make it more efficient and no repeating the base query?

Thanks

2
  • 2
    Try to clone a $query before fetching $total_paid and $total_unpaid (You'll get, for example, $query and $query2). Then use $query for $total_paid and $query2 for $total_unpaid. Here I presume that "cloning" is not "repeating". Commented Jan 5, 2016 at 9:40
  • well, why I can't think that way! :\. Thanks Gino! :D Commented Jan 5, 2016 at 9:43

2 Answers 2

1
$query = Transaction::ofBranch($this->merchant_id)->where(DB::raw('MONTH(created_at)'), Carbon::now()->subMonths($value)->format('m'));

Solution is to use clone, by which your original query will remain same and will not change, when you will extend this query.

E.g

$clone = clone $query;

You can use this instead $query Use this

$count = $clone ->count();

Not this:

$count = $query->count();

Others will be like

$total_paid = $clone->where('status',1)->sum('amount');

$total_unpaid = $clone->where('status',0)->sum('amount');
Sign up to request clarification or add additional context in comments.

Comments

0

You can try:

$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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.