find method

  1. @override
Future<List<T>> find({
  1. String? id,
  2. List<QueryFilter>? filters,
  3. List<String>? fields,
  4. Map<String, SortOrder>? sortOrder,
  5. Database? database,
  6. List<ColumnRelation>? relations,
})
override

Implementation

@override
Future<List<T>> find(
    {String? id,
    List<QueryFilter>? filters,
    List<String>? fields,
    Map<String, SortOrder>? sortOrder,
    Database? database,
    List<ColumnRelation>? relations}) async {
  final Database db = database != null ? database : this.database;

  if (id != null) {
    final queryResult = await db.query(this.entity.tableName,
        where: 'id = ?', whereArgs: [id], columns: fields);

    final relationResults = await this.findRelations(
        database: db,
        relations: relations,
        data: queryResult.length > 0 ? queryResult[0] : null);

    final dataResult = queryResult.map((result) {
      Map<String, dynamic> resultMap = {...result};

      this.columns.forEach((column) {
        final key = column.name;
        final relationElement =
            (relationResults != null ? relationResults : [])
                .where((relationResult) => relationResult['attribute'] == key)
                .toList();

        if (relationElement.length > 0) {
          resultMap[relationElement[0]['attribute']] =
              relationElement[0]['data'];
        } else {
          resultMap[key as String] = result[key];
        }
      });

      return getObject<T>(resultMap);
    }).toList();

    return dataResult;
  }

  final String? whereParameters =
      QueryFilter.getWhereParameters(this.columns, filters);
  final String? orderParameters =
      SortOrderUtil.getSortOrderParameters(sortOrder);

  if (whereParameters == null) {
    final dataResults = (await db.query(this.entity.tableName,
        orderBy: orderParameters, columns: fields));

    final List<String> dataIds =
        dataResults.map((dataResult) => dataResult['id'].toString()).toList();

    final relationData = await this.findRelationByParent(
        relations: relations as List<ColumnRelation>,
        dataIds: dataIds,
        orderParameters: orderParameters,
        database: db);

    return dataResults.map((queryResult) {
      Map<String, dynamic> resultMap = {...queryResult};

      (relationData ?? []).forEach((relationDataItem) {
        final availableRelationData = (relationDataItem['data'] ?? [])
            .where((relationItem) =>
                relationItem[relationDataItem['referencedColumn']] ==
                queryResult['id'])
            .toList();
        resultMap[relationDataItem['relation']] = availableRelationData;
      });

      return getObject<T>(resultMap);
    }).toList();
  }

  return findWhere(
      database: db,
      whereParameters: whereParameters,
      orderParameters: orderParameters,
      relations: relations);
}