Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Laravel Nova partition results by the count

I have a new Laravel Nova installation with a Property model. Properties have an attribute of 'country' and I want to show a partition metric on the 'country' col.

public function calculate(Request $request)
{
    return $this->count($request, Property::class, 'country','country');
}

All works, but it only sorts alphabetically by the country which rather than descending on the count which would make more sense.

Is there any way to sort the output?

like image 686
Drewster Avatar asked Nov 15 '25 05:11

Drewster


1 Answers

What you can do is :

public function calculate(Request $request)
{
    return $this->count($request, Property::orderBy('aggregate', 'desc'), 'country','country');
}

More information :
Nova will build the query as follow (nova/src/Metrics/Partition.php@aggregate):

 $results = $query->select(
            $groupBy, DB::raw("{$function}({$wrappedColumn}) as aggregate")
        )->groupBy($groupBy)->get();
  • $query is the given Builder instance of your model Property::orderBy(...) or Nova will make it for you when you pass the model Property::class
  • $function will be the method (count, min, max...)
  • $wrappedColumn will be the given column (country in your case)
  • $groupBy will be the given group by column (country) ...well you get it

At the end it will build :

$results = Property::orderBy('aggregate', 'desc')->select(
            'country', DB::raw("count(country) as aggregate")
        )->groupBy('country')->get();
like image 156
Clément Baconnier Avatar answered Nov 17 '25 19:11

Clément Baconnier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!