如何在现有领域数据库中添加新表?

时间:2018-05-22 10:52:31

标签: java android database realm

我正在使用realm 5.0.0我想在现有数据库中添加新表格,我该怎么做?

我试图找出解决方案,但我发现如何编辑表但是没有找到如何在迁移中添加新表。

Realm.init(this);
        RealmConfiguration config = new RealmConfiguration.Builder()
                .name("myrealm.realm")
                .schemaVersion(2)
                .migration(new RealmMigration() {
                    @Override
                    public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
                        if (oldVersion == 0) {
                            RealmObjectSchema personSchema = realm.getSchema().get("SKUItem");
                            personSchema
                                    .removeField("created_date")
                                    .removeField("modification_date")
                                    .addField("created_date", String.class)
                                    .addField("modification_date", String.class)
                            ;
                        } if (oldVersion == 1) {
                            // Here I want to add new Table 
                        }
                    }
                })
                .build();
        Realm.setDefaultConfiguration(config);

2 个答案:

答案 0 :(得分:3)

这将是这样的:

// Create a new class
schema.create("NewTable")
    .addField("id", int.class, FieldAttribute.PRIMARY_KEY)
    .addField("name", String.class, FieldAttribute.INDEXED);
olderVersion++;

答案 1 :(得分:0)

只需在migrationBlock中添加“ migration.create(“ NewTableName”,值:[])”。

示例:

var realm: Realm?
init() {
    do {
        let configuration = Realm.Configuration(schemaVersion: 2,
        migrationBlock: { migration, oldSchemaVersion in
            if (oldSchemaVersion == 1) {
                migration.create("ConnectedDeviceData", value: [])
            }
        })
        realm = try Realm(configuration: configuration)
    } catch {
      print("Realm Initialization Error: \(error)")
    }
}