TomTaila TomTaila - 6 months ago 147
Java Question

How can I recursively delete records using realm.io (Java/Android)?

How can I recursively delete records with one-to-many relationships using realm.io?

For example I have the following nested objects:

public class RealmUnit extends RealmObject {
private int id;
private RealmList<RealmChapter> chapters;
public RealmUnit() {
chapters = new RealmList<>();
}





public class RealmChapter extends RealmObject {
private int id;
private RealmList<RealmChapterGoal> chapterGoals;
public RealmChapter() {
chapterGoals = new RealmList<>();
}
}





public class RealmChapterGoal extends RealmObject {
private String type;
private String text;
public RealmChapterGoal() {}
}

Answer

Currently Realm doesn't cascading deletes, but it is on our TODO and is tracked here: https://github.com/realm/realm-java/issues/1104

So right now your only option is unfortunately a manually bottom-up approach.

for(RealmChapter chapter: realmUnit.getChapters) {
 chapter.getChapterGoals().clear();
}

realmUnit.getChapters().deleteAllFromRealm();
realmUnit.deleteFromRealm();

There is also a few more work-arounds described here: https://github.com/realm/realm-java/issues/2717