Task with many tags #1170
Replies: 3 comments 1 reply
-
Essentially, you have a many-to-many relationship between tasks and tags. You can implement that by using a junction table as explained here. Basically, you could write class NoteHasBookmarks extends Table {
IntColumn get note => integer().customConstraint('NOT NULL REFERENCES notes (id)')();
IntColumn get bookmark => integer().customConstraint('NOT NULL REFERENCES bookmarks (id)')();
@override
Set<Column> get primaryKey => {note, bookmark};
} Writing queries for general many-to-many relations can be a bit complicated (but moor has an example for that). If you pinpoint one side of the relation, it's much easier. For instance, you could load all bookmarks of a specific note by first joining |
Beta Was this translation helpful? Give feedback.
-
after hours warming up my brain, I got it that way, I don't know if it's a good practice, but it worked ... any suggestions for improvement? Future<void> writeWithBookmarks(NoteWithTags entry) {
return transaction(() async {
final note = entry.note;
final newNoteId = await into(notes).insert(note);
for (final item in entry.bookmark) {
await into(noteHasBookmarks)
.insert(NoteHasBookmark(note: newNoteId, bookmark: item));
}
});
} SELECT Stream<dynamic> watchWithBookmarks() {
final notesStream = select(notes).watch();
return notesStream.switchMap((carts) {
final idToCart = {for (var cart in carts) cart.id: cart};
final ids = idToCart.keys;
final entryQuery = select(noteHasBookmarks).join(
[
innerJoin(
bookmarks,
bookmarks.id.equalsExp(noteHasBookmarks.bookmark),
)
],
)..where(noteHasBookmarks.note.isIn(ids));
return entryQuery.watch().map((rows) {
final idToItems = <int, List<Bookmark>>{};
for (var row in rows) {
final item = row.readTable(bookmarks);
final id = row.readTable(noteHasBookmarks).note;
idToItems.putIfAbsent(id, () => []).add(item);
}
return [
for (var id in ids) NoteWithTags(idToCart[id], idToItems[id] ?? []),
];
});
});
} DELETE MANY WITH BOOKMARKS (using Primary key) Future<void> deleteSelected(List<int> ids) {
return transaction(() async {
await (delete(noteHasBookmarks)..where((r) => r.note.isIn(ids))).go();
await (delete(notes)..where((r) => r.id.isIn(ids))).go();
});
}``` |
Beta Was this translation helpful? Give feedback.
-
is it possible to create a task list that contains many tags? A task can contain multiple tags. How can I implement this using moor? Wish already thank you.
Example:
Beta Was this translation helpful? Give feedback.
All reactions