2

迁移实体并添加列后,我想在表中为新添加的列插入已存在记录的值。我怎样才能做到这一点?

例如,在这种情况下,对于数据库中已经存在的记录,我希望 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);
      }
    }
  );
4

2 回答 2

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' ''');
    });
  }
}
于 2020-10-22T08:34:28.960 回答
0

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

@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回调来创建初始数据。

于 2020-10-20T07:12:22.850 回答