如何使用嵌套查询从SQFlite数据库中获取数据?

时间:2019-06-27 06:48:51

标签: android sqlite flutter sqflite

我想从sqflite数据库中获取位置和与位置相关联的网关。

我试图先获取所有位置,然后再尝试为每个位置获取网关。我确实收到了正确的数据。 但是问题是,即使使用asyncawait,方法的return语句也会先调用,然后再执行所有操作。

下面是获取位置和网关的代码:

    Future<List<Location>> fetchAllLocationFromGroupId(int groupId) async {
    List<Location> locations = List();
    Database db = await database;
    var locationResult = await db.query(DatabaseData.LOCATION_TABLE_NAME, columns: [
      DatabaseData.LOCATION_ID,
      DatabaseData.LOCATION_NAME,
      DatabaseData.LOCATION_ALIAS,
      DatabaseData.LOCATION_SET_DEFAULT,
      DatabaseData.LOCATION_IS_ACTIVE,
      DatabaseData.LOCATION_GROUP_ID
    ]);

    locationResult.forEach((row) async {
      Location location = Location.fromMap(row);
      List<Gateway> gateways = List();
      var gatewayResult =
          await db.query(DatabaseData.GATEWAY_TABLE_NAME, columns: [
        DatabaseData.GATEWAY_ID,
        DatabaseData.GATEWAY_NAME,
        DatabaseData.GATEWAY_ALIAS,
        DatabaseData.GATEWAY_MAC,
        DatabaseData.GATEWAY_CREATED_AT,
        DatabaseData.GATEWAY_UPDATED_AT,
        DatabaseData.GATEWAY_LOCATION_ID,
        DatabaseData.GATEWAY_USER_ID
      ]);

      gatewayResult.forEach((gateway) {
        gateways.add(Gateway.fromMap(gateway));
      });

      /*gatewayResult.then((List<Map<String, dynamic>> maps) {
        for (var gateway in maps) {
          Gateway gateway1 = Gateway.fromMap(gateway);
          print(gateway1);
          gateways.add(gateway1);
        }
      });*/

      location.gateways = gateways;
      print(
          "DBHelper $groupId -> Location id -> ${location.id} and gateways-> ${location.gateways[0].gatewayAlias}");
      locations.add(location);
    });
    return locations;
  }

0 个答案:

没有答案