实际上,我试图从表(父表)中删除一个条目,与此同时,我想从与该父表关联的所有表(子表)中删除所有条目。但是问题是动态领域不支持级联删除。所以问题是,如何在动态领域中级联删除?
我的方法是递归。但是我愿意接受其他选择。
public void cascadeDelete (DynamicRealmObject dynamicObj){
Realm realm = Realm.getDefaultInstance();
DynamicRealm dynamicRealm =
DynamicRealm.getInstance(realm.getConfiguration());
try {
String fieldNames[] = dynamicObj.getFieldNames();
for(String field : fieldNames) {
if(dynamicObj.getFieldType(field).equals(RealmFieldType.LIST)) {
List<DynamicRealmObject> dynamicRealmObjects =
dynamicObj.getList(field);
List<DynamicRealmObject> newList = new RealmList<>();
newList.addAll(dynamicRealmObjects);
for(int k = 0; k < newList.size(); k++) {
String primaryKey =
Objects.requireNonNull(dynamicRealm.getSchema().get(field))
.getPrimaryKey();
String primaryId =
Objects.requireNonNull(newList.get(k)).getString(primaryKey);
DynamicRealmObject filterObj =
dynamicRealm.where(field).equalTo(primaryKey,
primaryId).findFirst();
if(filterObj != null) {
cascadeDelete(filterObj);
}
}
}
}
dynamicRealm.beginTransaction();
dynamicObj.deleteFromRealm();
dynamicRealm.commitTransaction();
} catch(Exception e) {
e.printStackTrace();
} finally {
dynamicRealm.close();
realm.close();
}
}