Sortable with nested relations

How can I use sortable with multiple relations?
return $table
->columns([
//
Tables\Columns\TextColumn::make('type.year.name')->label('Année')->sortable(),
Tables\Columns\TextColumn::make('type.name')->label('Type')->sortable(),
Tables\Columns\TextColumn::make('name')->label('Region')->sortable(),
Tables\Columns\TextColumn::make('description'),
])
return $table
->columns([
//
Tables\Columns\TextColumn::make('type.year.name')->label('Année')->sortable(),
Tables\Columns\TextColumn::make('type.name')->label('Type')->sortable(),
Tables\Columns\TextColumn::make('name')->label('Region')->sortable(),
Tables\Columns\TextColumn::make('description'),
])
when I try to sort type.year.name it gives me : Column not found: 1054 Unknown column 'pk_types.year_id' which is normal because there's no column year_id in table regions
5 Replies
Dan Harrin
Dan Harrin2y ago
you would need to pass a custom sortable query function in v3 it is fixed.
Pasteko
PastekoOP2y ago
Is this a good start? ->sortable(query: function (Builder $query, string $direction): Builder { return $query ->orderBy('last_name', $direction) ->orderBy('first_name', $direction); })
Dan Harrin
Dan Harrin2y ago
yeah but you need to work out how to sort on a deeply nested relationship its tricky with Eloquent
Pasteko
PastekoOP2y ago
Could something like this work?
Tables\Columns\TextColumn::make('type.year.name')->label('Année')
->sortable(query: function (Builder $query, string $direction): Builder {
return $query
->select('pk_years.name')
->join('pk_types', 'pk_types.id', 'type_id')
->join('pk_years', 'pk_years.id', 'pk_types.year_id')
->orderBy('pk_years.name', $direction);
})
Tables\Columns\TextColumn::make('type.year.name')->label('Année')
->sortable(query: function (Builder $query, string $direction): Builder {
return $query
->select('pk_years.name')
->join('pk_types', 'pk_types.id', 'type_id')
->join('pk_years', 'pk_years.id', 'pk_types.year_id')
->orderBy('pk_years.name', $direction);
})
Dan Harrin
Dan Harrin2y ago
i doubt you need the select
Want results from more Discord servers?
Add your server