F
Filament15mo ago
Karim98

Summarize JSON

How can I Sum a specific key in a JSON column? Tables\Columns\TextColumn::make('extracted_data.total_characters') ->label('Characters') ->toggleable(isToggledHiddenByDefault: true) ->sortable() ->searchable() ->summarize(Summarizer::make() ->label('Total Characters') ->using(fn (Builder $query): string => $query->sum('extracted_data.total_characters'))),
6 Replies
Dennis Koch
Dennis Koch15mo ago
You probably need to do this yourself via ->getStateUsing(). ->sum() works on the DB
Karim98
Karim98OP15mo ago
I can't find something called ->getStateUsing, I only found ->getState() Can you show an example?
Dennis Koch
Dennis Koch15mo ago
TextColumn::make('your_data')->getStateUsing(fn ($record) => ....)
TextColumn::make('your_data')->getStateUsing(fn ($record) => ....)
Karim98
Karim98OP15mo ago
I really appreciate your help but I think this is not what I am looking for, Lets say I got the state, How can I show them as a Summary of all of the rows summed together?
Dennis Koch
Dennis Koch15mo ago
Oh I didn’t see you were talking about summarizers. I thought you wanted sums for relations. Haven’t worked with summarizers yet. I guess you can write your own to work on the json data but I am not sure.
Karim98
Karim98OP15mo ago
Here's the solution: Tables\Columns\TextColumn::make('extracted_data.translated_characters') ->label('Translate Characters') ->toggleable(isToggledHiddenByDefault: true) ->summarize( Summarizer::make() ->label('Translate Characters') ->using(function () { $records = Request::all()->where('type', 'Translate'); $translateSum = $records->sum(function ($record) { $extractedData = $record->extracted_data; return $extractedData['translated_characters'] ?? 0; }); return $translateSum; }) ),
Want results from more Discord servers?
Add your server