简体   繁体   中英

how to save nested complex JSON data in a sqlite database on flutter

I have nested complex JSON data. I made a model for them and I can serialize and deserialize.

I read the document of flutter and examples of saving data in SQLite but all of the examples are for simple JSON data, not complex data.

I created the two tables for this (order_table, order_item_table) and saves the order_id key in order_item_table

But it's a little strange to query that gives me a nested map.

How can I do it?

class Order {
  int id;
  int userId;
  OrderStatus status;
  List<OrderItem> orderItems;
  DateTime createdAt;
  DateTime updatedAt;

  Order({
    this.id,
    this.userId,
    this.status,
    this.orderItems,
    this.createdAt,
    this.updatedAt,
  });

  factory Order.fromJson(Map<String, dynamic> json) => new Order(
        id: json["id"],
        userId: json["user_id"],
        status: OrderStatusValues.map[json["status"]],
        orderItems: new List<OrderItem>.from(
            json["order_items"].map((x) => OrderItem.fromJson(x))),
        createdAt: DateTime.parse(json["created_at"]),
        updatedAt: DateTime.parse(json["updated_at"]),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "user_id": userId,
        "status": OrderStatusValues.reverse[status],
        "order_items":
            new List<dynamic>.from(orderItems.map((x) => x.toJson())),
        "created_at": createdAt.toIso8601String(),
        "updated_at": updatedAt.toIso8601String(),
      };
}

class OrderItem {
  int id;
  int orderId;
  int productId;
  int qty;
  Product product;
  OrderItemStatus status;
  String comment;
  DateTime createdAt;
  DateTime updatedAt;

  OrderItem({
    this.id,
    this.orderId,
    this.productId,
    this.qty,
    this.product,
    this.status,
    this.comment,
    this.createdAt,
    this.updatedAt,
  });

  factory OrderItem.fromJson(Map<String, dynamic> json) => new OrderItem(
        id: json["id"],
        orderId: json["order_id"],
        productId: json["product_id"],
        qty: json["qty"],
        product: Product.fromJson(json['product']),
        status: orderItemStatusValues.map[json["status"]],
        comment: json["comment"] == null ? null : json["comment"],
        createdAt: DateTime.parse(json["created_at"]),
        updatedAt: DateTime.parse(json["updated_at"]),
      );



  Map<String, dynamic> toJson() => {
        "id": id,
        "order_id": orderId,
        "product_id": productId,
        "qty": qty,
        'product': product.toJson(),
        "status": orderItemStatusValues.reverse[status],
        "comment": comment == null ? null : comment,
        "created_at": createdAt.toIso8601String(),
        "updated_at": updatedAt.toIso8601String(),
      };
}

I created the relational table like this:

Future<Database> getDatabase() async {
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'stock.db');

    String sql = '''
    CREATE TABLE $_tableName (
      order_id INTEGER PRYMARY KEY,
      user_id INTEGER,
      order_status TEXT,
      created_at TEXT,
      updated_at TEXT
    )
    ''';

    String sql2 = '''
      CREATE TABLE $_order_item_table (
        order_item_id INTEGER PRYMARY KEY,
        order_id INTEGER,
        product_id INTEGER,
        qty INTEGER,
        order_item_status TEXT,
        comment TEXT,
        order_item_created_at TEXT,
        order_item_updated_at TEXT
      )
    ''';
    database = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
      await db.execute(sql);
      await db.execute(sql2);
    });

    return database;
  }

You've created two SQL tables, but they are not related until you query them as such (eg using INNER JOIN ). You will have to 'manually' translate between a nested JSON representation and a relational SQL query (and vice versa). Have you considered an alternative database, more aligned with your JSON structure, such as Cloud Firestore ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM