withFields method

ProcessedTableManager<$Database, $Table, $Dataclass, $FilterComposer, $OrderingComposer, $ComputedFieldComposer, $CreateCompanionCallback, $UpdateCompanionCallback, $DataclassWithReferences, $DataclassWithReferences, $CreatePrefetchHooksCallback> withFields(
  1. Iterable<BaseComputedField<Object, $Table>> computedFields
)

Add computed fields to the statement which will be used to add additional columns to the query These columns will be returned in the result set and can be used in filters/orderings

/// Filter users who are in an admin group
final inAdminGroup = db.managers.users.computed field((a) => a.group.isAdmin);
final users = db.managers.users.withComputedFields([inAdminGroup]).filter(inAdminGroup.filter(true)).get();

/// Aggregate the number of users in each group
final userCount = db.managers.group.computed field((a) => a.users((a) => a.id.count()));
final groups = db.managers.group.withComputedFields([userCount]).get();
for (final (group, refs) in groups) {
  final count = userCount.read(refs);
}

In this example:

  • The inAdminGroup computed field filters users directly in the database, ensuring that only users in the admin group are retrieved.
  • The userCount computed field aggregates the number of users in each group within the database, providing the count directly without needing to load all user data into your application.

Implementation

ProcessedTableManager<
        $Database,
        $Table,
        $Dataclass,
        $FilterComposer,
        $OrderingComposer,
        $ComputedFieldComposer,
        $CreateCompanionCallback,
        $UpdateCompanionCallback,
        $DataclassWithReferences,
        $DataclassWithReferences,
        $CreatePrefetchHooksCallback>
    withFields(Iterable<BaseComputedField<Object, $Table>> computedFields) {
  final joinBuilders =
      computedFields.map((e) => e._joinBuilders).expand((e) => e).toSet();
  final addedColumns = computedFields.map((e) => e._expression).toSet();
  return ProcessedTableManager($state.copyWith(
          addedColumns: $state.addedColumns.union(addedColumns),
          joinBuilders: $state.joinBuilders.union(joinBuilders)))
      .withReferences();
}