Home > Blockchain >  Laravel sum multiple withCount results
Laravel sum multiple withCount results

Time:11-23

I want to order by the sum of multiple whereCount results. This is my whereCount

$q->withCount(['ordered', 'favorites']);

I wan to sum these ordered_count favorites_count and order by this result. I am not very good at using SQL so i need some help. If this is possible using eloquent query builder than that is even better.Thank you.

CodePudding user response:

you can use orderByRaw to order by the sum:

$q->withCount(['ordered', 'favorites'])
->orderByRaw('(ordered_count   favorites_count) desc')
->get();
  • Related