How To Create Flutter Moor Relationship With One-To-Many Join

不羁岁月 提交于 2021-02-18 17:10:30

问题


I have a table Category which is Related to a Task table in a one-to-many relationship and I am attempting to perform a join using Moor.

I would like to return a list for the list of tasks that match a category. How do I do it?

      Stream<List<CategoryWithTask>> watchAllCategories() {
        return (select(categories)
              ..orderBy(([
                (c) => OrderingTerm(expression: c.name),
              ])))
            .join([leftOuterJoin(tasks, tasks.categoryId.equalsExp(categories.id))])
            .watch()
            .map((rows) => rows.map(
                  (row) {
                    return CategoryWithTask(
                        category: row.readTable(categories),
                        task: row.readTable(tasks)); // How do I modify this line to return a list of tasks corresponding to a category?
                  },
                ).toList());
      }

回答1:


I managed to find a way with the support of the guys at Flutter Moor after creating an issue on Github. Below is the working code;

  Stream<List<CategoryWithTasks>> watchAllCategories() {
    return (select(categories)
          ..orderBy(([
            (c) => OrderingTerm(expression: c.name),
          ])))
        .join([leftOuterJoin(tasks, tasks.categoryId.equalsExp(categories.id))])
        .watch()
        .map((rows) {
          final groupedData = <Category, List<Task>>{};

          for (final row in rows) {
            final category = row.readTable(categories);
            final task = row.readTable(tasks);

            final list = groupedData.putIfAbsent(category, () => []);
            if (task != null) list.add(task);
          }

          return [
            for (final entry in groupedData.entries)
              CategoryWithTasks(category: entry.key, tasks: entry.value)
          ];
        });
  }


来源:https://stackoverflow.com/questions/60252122/how-to-create-flutter-moor-relationship-with-one-to-many-join

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!