我正在尝试更新我的RelamObject(本例中是RealmCase)中的一个属性。我已经尝试了下面的代码,它看起来像我的Realm中没有更新,虽然我在RealmPatientInfo表中看到了一个新对象,但是我的RealmCase没有创建任何关系。在Realm中执行更新时出错
RealmCase realmCase = new RealmCase();
realmCase.setId(getId());
realmCase.setPatientInfo(new RealmPatientInfo(patientInfo));
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.copyToRealmOrUpdate(realmCase);
realm.commitTransaction();
realm.close();
我也尝试了以下,但得到一个异常,说价值不是由领域管理。
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
RealmQuery<RealmCase> query = realm.where(RealmCase.class);
RealmCase persistedCase = query.findFirst();
persistedCase.setPatientInfo(new RealmPatientInfo(patientInfo));
realm.copyToRealmOrUpdate(realmCase);
realm.commitTransaction();
realm.close();
我也想删除旧patientInfo对象(参考和在RealmPatientInfo表中的条目),下面是我在这个尝试,尽管从我之前错误使我从测试的一部分。
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
RealmQuery<RealmCase> query = realm.where(RealmCase.class);
RealmCase persistedCase = query.findFirst();
if(persistedCase.getPatientInfo() != null) {
persistedCase.getPatientInfo().removeFromRealm();
persistedCase.setPatientInfo(null);
}
persistedCase.setPatientInfo(new RealmPatientInfo(patientInfo));
realm.copyToRealmOrUpdate(realmCase);
realm.commitTransaction();
realm.close();
任何意见是非常感谢。
您的'新的RealmPatientInfo(patientInfo)'不是由Realm管理的,必须为您管理,以便将其设置为关系的其他成员。 – EpicPandaForce