rappasoft / laravel-livewire-tables

A dynamic table component for Laravel Livewire
https://rappasoft.com/docs/laravel-livewire-tables/v2/introduction
MIT License
1.71k stars 320 forks source link

Sorting by accessor attribute not working #73

Closed Gerto closed 3 years ago

Gerto commented 3 years ago

Laravel version 8 Livewire Tables version 0.3.1

I have the following table:

            Column::make('id')
                ->searchable()
                ->sortable(),
            Column::make('Title')
                ->searchable()
                ->sortable(),
            Column::make('Min. Bid','MinBid')
                ->searchable()
                ->sortable(),

'id' and 'title' are normal fields and sorting works perfectly as expected, 'MinBid' is an accessor defined in the model and when I click it to sort, the table goes back to the default sorting but no actual sorting happens.

Here's the code where accessor is defined:

    public function getMinBidAttribute(){
      return Auction::where('product_id',$this->id)->min('closing_bid');
    }

Thanks for this package!

ConnorHowell commented 3 years ago

Not sure if this would be possible as sorting & searching is done via the database fields; not the eloquent models.

I've not had a chance to try it myself but seeing as query() needs to return an instance of Eloquent\Builder could you not try doing a join? By using an accessor to get this attribute you're also doing this incredibly inefficiently as you are doing 1 query for each product in the collection (See: N+1 Problem)

rappasoft commented 3 years ago

I haven't tried but see if adding it to the $appends array of the model effects the queries ability to see it. If not, you can return a callback to the sortable() method.