Home > Mobile >  laravel - how to sort by count of relation with WHERE
laravel - how to sort by count of relation with WHERE

Time:10-08

I'm running this query filtering relation entries. It's working good.

$places = Place::
                with([
                  'mytickets' => function($q) use ($from, $to) {
                    $q->whereBetween('used_at', [$from, $to]);
                  }])
                ->get();

So now I want to get results sorting DESC by the count of mytickets.

Is it possible?

CodePudding user response:

Yes, it's possible. Try something like : (i haven't tested)

$places = Place::with(['mytickets' => function($q) use ($from, $to) {
                 $q->whereBetween('used_at', [$from, $to]);
               }
          ])
          ->get()
          ->sortBy(function($places){
               return $places->mytickets->count();
          });
  • Related