computedField<T extends Object> method

ComputedField<T, $Table> computedField<T extends Object>(
  1. Expression<T> a(
    1. $ComputedFieldComposer a
    )
)

Create an computed field for adding additional columns to the query

The computed field and computed fieldWithConverter methods allow you to create computed fields that add additional columns to a query. These columns are computed directly by the database. This approach has significant performance benefits compared to querying all the data and performing the calculations yourself in your Dart code.

Example

Consider the following example where we use the computed field method to filter users who are in an admin group and to aggregate the number of users in each group:

/// 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.

By leveraging these database calculations, you can achieve faster query performance and more efficient resource usage in your application.

See also: computed fieldWithConverter for computed fields on columns with type converters

Implementation

ComputedField<T, $Table> computedField<T extends Object>(
  Expression<T> Function($ComputedFieldComposer a) a,
) {
  final composer = $state.createComputedFieldComposer();
  final expression = a(composer);
  return ComputedField(expression, composer.$joinBuilders.toSet());
}