我是 flutter 的新手,想创建 Category 表,其中外键是同一个表的 id 来创建子类别。我不知道如何在颤振中使用此类表创建数据。下面是我的分类模型类代码和databaseHelper类代码。
类别型号代码:
final String tableCategory = 'category';
class CategoryModel {
final int? id;
final String name;
final String desc;
final int? parentId;
final bool isActive;
final DateTime createdTime;
final String createdBy;
CategoryModel(
{this.id,
required this.name,
required this.desc,
this.parentId,
required this.isActive,
required this.createdTime,
required this.createdBy});
factory CategoryModel.fromMap(Map<String, dynamic> json) => CategoryModel(
id: json["id"],
name: json["name"],
desc: json["desc"],
parentId: json["parentId"],
isActive: json["isActive"] == 1,
createdTime: DateTime.parse(json["createdTime"]),
createdBy: json["createdBy"],
);
Map<String, dynamic> toMap() => {
"id": id,
"name": name,
"desc": desc,
"parentId": parentId,
"isActive": isActive ? 1 : 0,
"createdTime": createdTime.toIso8601String(),
"createdBy": createdBy,
};
}
databaseHelper 类代码:
import 'package:budget_app/model/categoryModel.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
class DB {
static final DB instance = DB._init();
static Database? _database;
DB._init();
Future<Database> get database async{
if(_database != null) return _database!;
_database = await _initDB('budget.db');
return _database!;
}
Future<Database> _initDB(String filePath) async {
final dbPath = await getDatabasesPath();
final path = join(dbPath, filePath);
return await openDatabase(path, version: 1, onCreate: _onCreate, onConfigure: _onConfigure);
}
Future _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE $tableCategory(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
desc TEXT NOT NULL,
parentId INTEGER,
FOREIGN KEY(parentId) REFERENCES $tableCategory (id) ON DELETE NO ACTION ON UPDATE NO ACTION,
isActive BOOLEAN NOT NULL,
createdTime DATETIME DEFAULT (cast(strftime('%s','now') as int)),
createdBy TEXT NOT NULL,
)
''');
}
Future _onConfigure(Database db) async {
// Add support for cascade delete
await db.execute("PRAGMA foreign_keys = ON");
}
//Custom Category Functions
Future<bool> insertCategory(CategoryModel categoryModel) async {
final db = await instance.database;
db.insert("Categories", categoryModel.toMap());
return true;
}
Future<List<CategoryModel>> getCategory() async {
final db = await instance.database;
final List<Map<String, Object?>> categories = await db.query("Categories");
return categories.map((e) => CategoryModel.fromMap(e)).toList();
}
Future<int> updateCategory(CategoryModel categoryModel) async {
final db = await instance.database;
return db.update(
tableCategory,
categoryModel.toMap(),
where: 'id = ?',
whereArgs: [categoryModel.id],
);
}
Future<int> deleteCategory(int id) async {
final db = await instance.database;
return await db.delete(
tableCategory,
where: 'id = ?',
whereArgs: [id],
);
}
Future close() async {
final db = await instance.database;
db.close();
}
}