Docs: Fix group by Dartt examples

This commit is contained in:
Simon Binder 2022-04-25 10:49:11 +02:00
parent f13ecced6f
commit d23028a5bb
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
2 changed files with 47 additions and 34 deletions

View File

@ -0,0 +1,37 @@
import 'package:drift/drift.dart';
import 'tables/filename.dart';
extension GroupByQueries on MyDatabase {
// #docregion countTodosInCategories
Future<void> countTodosInCategories() async {
final amountOfTodos = todos.id.count();
final query = select(categories).join([
innerJoin(
todos,
todos.category.equalsExp(categories.id),
useColumns: false,
)
]);
query
..addColumns([amountOfTodos])
..groupBy([categories.id]);
final result = await query.get();
for (final row in result) {
print('there are ${row.read(amountOfTodos)} entries in'
'${row.readTable(categories)}');
}
}
// #enddocregion countTodosInCategories
// #docregion averageItemLength
Stream<double> averageItemLength() {
final avgLength = todos.content.length.avg();
final query = selectOnly(todos)..addColumns([avgLength]);
return query.map((row) => row.read(avgLength)!).watchSingle();
}
// #enddocregion averageItemLength
}

View File

@ -174,6 +174,8 @@ with the right table by default).
## Group by
{% assign snippets = 'package:moor_documentation/snippets/queries.dart.excerpt.json' | readString | json_decode %}
Sometimes, you need to run queries that _aggregate_ data, meaning that data you're interested in
comes from multiple rows. Common questions include
@ -193,26 +195,7 @@ We're going to select all categories and join each todo entry for each category.
We only care about how many there are. By default, drift would attempt to read each todo item when it appears
in a join.
```dart
final amountOfTodos = todos.id.count();
final query = db.select(categories).join([
innerJoin(
todos,
todos.category.equalsExp(categories.id),
useColumns: false,
)
]);
query
..addColumns([amountOfTodos])
..groupBy([categories.id]);
final result = await query.get();
for (final row in result) {
print('there are ${row.read(amountOfTodos)} entries in ${row.readTable(todos)}');
}
```
{% include "blocks/snippet" snippets = snippets name = 'countTodosInCategories' %}
To find the average length of a todo entry, we use `avg`. In this case, we don't even have to use
a `join` since all the data comes from a single table (todos).
@ -223,11 +206,4 @@ Drift provides a special method for this case - instead of using `select`, we us
The "only" means that drift will only report columns we added via "addColumns". In a regular select,
all columns from the table would be selected, which is what you'd usually need.
```dart
Stream<double> averageItemLength() {
final avgLength = todos.content.length.avg();
final query = selectOnly(todos)..addColumns([avgLength]);
return query.map((row) => row.read(avgLength)).watchSingle();
}
```
{% include "blocks/snippet" snippets = snippets name = 'averageItemLength' %}