【问题标题】:flutter moor add initial data after migrationflutter moor 在迁移后添加初始数据
【发布时间】:2020-08-03 15:33:52
【问题描述】:

迁移实体并添加列后,我想在表中为新添加的列插入已存在记录的值。 我该怎么做?

例如,在这种情况下,对于数据库中已存在的记录,我希望 dueDate 列值为 DateTime(2019,1,1)。

class Todos extends Table {
  IntColumn get id => integer().autoIncrement()();
  TextColumn get title => text().withLength(min: 6, max: 10)();
  TextColumn get content => text().named('body')();
  IntColumn get category => integer().nullable()();
  DateTimeColumn get dueDate => dateTime().nullable()(); // new, added column
}
  int get schemaVersion => 2; // bump because the tables have changed

  @override
  MigrationStrategy get migration => MigrationStrategy(
    onCreate: (Migrator m) {
      return m.createAllTables();
    },
    onUpgrade: (Migrator m, int from, int to) async {
      if (from == 1) {
        // we added the dueDate property in the change from version 1
        await m.addColumn(todos, todos.dueDate);
      }
    }
  );

【问题讨论】:

    标签: flutter flutter-moor


    【解决方案1】:

    等待 m.addColumn 和 .then() 你可以使用customStatement()

    onUpgrade: (Migrator m, int from, int to) async {
      if (from == 1) {
        await m.addColumn(todos, todos.dueDate).then((value) async {
            var dateInTheFuture = (new DateTime.utc(2022, 12, 24).millisecondsSinceEpoch / 1000).round();
            await customStatement(''' UPDATE todos SET dueDate = '$dateInTheFuture' ''');
        });
      }
    }
    

    【讨论】:

      【解决方案2】:

      我不知道此操作有任何辅助方法,但您可以在 Migrator 对象中使用issueCustomQuery() 方法。

      @override
        MigrationStrategy get migration => MigrationStrategy(
              onCreate: (Migrator m) async { ... }},
              onUpgrade: (Migrator m, int from, int to) async {
                 ...   
                 final sql = "YOUR CUSTOM SQL"
                 await m.issueCustomQuery(sql);  
                 ...
                },
            );
      

      如果这是第一个架构版本,您可以使用 onCreate 回调来创建初始数据。

      【讨论】:

        猜你喜欢
        • 2021-07-26
        • 2017-02-02
        • 1970-01-01
        • 2018-06-27
        • 1970-01-01
        • 2014-11-15
        • 1970-01-01
        • 2016-02-09
        • 1970-01-01
        相关资源
        最近更新 更多