how to make custom column sortable
I have a custom column in my table, which i want to be able to sort it.
the custom column contains numbers from a calculation, so they are not part of the fields of the model represented in the table
12 Replies
define a sortable() callback which does the SQL necessary to sort
where should i define it? inside the custom column, or when calling it in the table?
not sure how to do it
my code at the moment:
view:
what is gamesCount
you define it when building the table
btw... there is no need for a custom column for this
oh really
what is gamesCount
is a function inside team model.
a game always has a team_a field and team_b field which are relations of the team table
so to get the games where that team is in, i call this function
cuz idk how to set a hasmany/belongstomany relationship based on 2 possible columns
idk if im explaining myself
dont worry, ill try to fix it. thanks for ur time
the way youre doing it is not very optimal, because its actually causing an n+1 issue
to start with, add two hasmany relationships on your model, gamesA and gamesB, each using just one foreign key
then on the filament table column, add
->counts(['gamesA', 'gamesB'])
then, ->getStateUsing(fn ($record) => $record->games_a_count + $record->games_b_count)
then, ->sortable(true, fn ($query, $direction) => $query->orderByRaw('games_a_count + games_b_count ' . $direction))
Solution
that should be it, and you dont need games() or gamesCount() functions
thanks. ill try it. but how im causing the n+1 issue?
because you're making a query for every table row
that is awesome, works like a charm
how the hell u actually solved it without even knowing my code lol
i hope one day can be like u ^^
this is how it looks like now:
haha its ok