findById method

  1. @override
Future<M?> findById(
  1. D id, {
  2. M? existModel,
  3. bool includeSoftDeleted = false,
})
override

find single model by id if existModel is given, existModel will be filled and returned, otherwise a new model will be returned.

Implementation

@override
Future<M?> findById(D id,
    {M? existModel, bool includeSoftDeleted = false}) async {
  var clz = modelInspector.meta(className)!;

  var idFields = clz.idFields;
  var idFieldName = idFields.first.name;
  var tableName = clz.tableName;
  var softDeleteField = clz.softDeleteField;

  var allFields = clz.allFields(searchParents: true)
    ..removeWhere((f) => f.notExistsInDb);

  var columnNames = allFields.map((f) => f.columnName).join(',');

  var sql = 'select $columnNames from $tableName where $idFieldName = $id';
  var params = <String, dynamic>{};

  if (softDeleteField != null && !includeSoftDeleted) {
    sql += ' and ${softDeleteField.columnName}=@_deleted ';
    params['_deleted'] = false;
  }

  _logger.fine('findById: $className [$id] => $sql');

  var rows = await db.query(sql, params, tableName: tableName);

  if (rows.isNotEmpty) {
    return toModel(rows[0], allFields, className, existModel: existModel);
  }
  return null;
}