7

我有一个表类别,它与一对多关系中的任务表相关,我正在尝试使用 Moor 执行连接。

我想返回一个与类别匹配的任务列表。我该怎么做?

      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());
      }
4

1 回答 1

14

在 Github 上创建问题后,我设法在 Flutter Moor 人员的支持下找到了一种方法。以下是工作代码;

  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)
          ];
        });
  }
于 2020-02-19T15:06:32.633 回答