Help with one-to-many query #3277
-
Hello I have been looking for days for a official way of doing a one-to-many select but everything I find seems like a hack. Here's some of the best i could find: I checked the Official docs, videos and some offical examples, but everyone one seems to do it differently, while having no suggestion in the docs. Here's some simple tables for an example. @DataClassName('UserEntity')
class Users extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get username => text().unique()();
}
@DataClassName('PostEntity')
class Posts extends Table {
IntColumn get id => integer().autoIncrement()();
IntColumn get userId => integer().references(Users, #id)();
TextColumn get content => text()();
}
class UserWithPosts {
final UserEntity user;
final List<PostEntity> posts;
UserWithPosts({
required this.user,
required this.posts,
});
} Here's how i'm getting the data I want, can do this with a Future<List<UserWithPosts>> getUsersWithPosts() async {
/// My actual query is more complicated than this, this is why `dbquery`
/// exists and it's not just `final rows = await select(users).get();`
final dbQuery = select(users);
final rows = await dbQuery.get();
final List<PostEntity> allPosts = await select(posts).get();
return rows.map((row) {
return UserWithPosts(
row,
allPosts.where((p) => p.userId == row.id).toList(),
);
}).toList();
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The new manager API makes this easy.
|
Beta Was this translation helpful? Give feedback.
The new manager API makes this easy.
You need the latest version of drift.