How to avoid duplicate queries

I am using table with TextColumn, i am fetching custom data from another table based on the id of the $record. For some reason it gives me duplicate entries despite using callback. Any help please?
TextColumn::make('specialitie_id')
->formatStateUsing(
fn($record) => Speciality::find($record->speciality->first()->parent_id, ['name'])
)
->label('Speciality'),
TextColumn::make('specialitie_id')
->formatStateUsing(
fn($record) => Speciality::find($record->speciality->first()->parent_id, ['name'])
)
->label('Speciality'),
No description
4 Replies
Majid Al Zariey
Majid Al Zariey4mo ago
This is normal as you are using a query in the formatStateUsing I recommend using join relationship with left join option by modifying the Resource query
kingtox
kingtox4mo ago
it doesn't happened in V2, strange. i have a large data including relationship so are you sure it's normal and won't affect the performance etc?
Povilas K
Povilas K4mo ago
@kingtox weird to hear that it doesn't happen in v2, as there's clearly a separate DB query for every record. And yes, my recommendation is the same, to change the initial query to use join, probably @kingtox I've tried to reproduce it to create a demo video, so here's how you can load that parent relationship directly from TextColumn:
class Job extends Model
{
public function speciality(): BelongsTo
{
return $this->belongsTo(Speciality::class);
}
}

class Speciality extends Model
{
public function parent(): BelongsTo
{
return $this->belongsTo(Speciality::class, 'parent_id');
}
}

// JobResource in Filament:
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name'),
Tables\Columns\TextColumn::make('speciality.parent.name'),
])
class Job extends Model
{
public function speciality(): BelongsTo
{
return $this->belongsTo(Speciality::class);
}
}

class Speciality extends Model
{
public function parent(): BelongsTo
{
return $this->belongsTo(Speciality::class, 'parent_id');
}
}

// JobResource in Filament:
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name'),
Tables\Columns\TextColumn::make('speciality.parent.name'),
])
Povilas K
Povilas K4mo ago
will load only two queries for the relationship, no matter the amount of rows
No description
Want results from more Discord servers?
Add your server
More Posts