FilamentF
Filament17mo ago
lmtc

HasMany Table Relationship pivot/group RelationManager

I have a table like:
form_id | session_id | field_name | field_value
5 | 123 | first_name | john
5 | 123 | last_name | smith

but I need it to be grouped like
session_id | first_name | last_name

any help would be appreciated!
Solution
I got this working:
protected function getTableQuery()
return $this->record->submissions()->groupBy('session_id')->getQuery();
}

protected function getTableColumns(): array
{
$fieldNames = $this->record->submissions()
    ->pluck('field_name')
    ->unique();

$columns = [];

foreach ($fieldNames as $field) {
    $columns[] = TextColumn::make($field)
        ->label($field)
        ->getStateUsing(fn($record) => $this->getFieldValue($record, $field));
}

return $columns;
}

protected function getFieldValue(FormSubmissions $record, string $field)
{
return $record->where('session_id', $record->session_id)
    ->where('field_name', $field)
    ->value('field_value');
}

public function table(Table $table): Table
{
return $table
    ->query($this->getTableQuery())
    ->columns($this->getTableColumns())
    ->actions([
        DeleteAction::make()
            ->action(function (FormSubmissions $record) {
                FormSubmissions::where('session_id', $record->session_id)
                    ->where('form_id', $record->form_id)
                    ->delete();
            })
            ->requiresConfirmation()
            ->label('Delete'),
    ])
    ->bulkActions([
        BulkAction::make('deleteAll')
            ->action(function (Collection $records) {
                // Retrieve unique session IDs from the selected records
                $sessionIds = $records->pluck('session_id')->unique();

                // Delete all submissions related to these session IDs
                FormSubmissions::whereIn('session_id', $sessionIds)->delete();
            })
            ->requiresConfirmation()
            ->label('Delete All'),
    ]);
}
Was this page helpful?