Search code examples
androidrealm

How to prevent delete of an object referenced from another object in Realm?


I have an object Person and in this Person i have a City instance. If i create a city and set it to a person, later i can delete the city without deleting the person first or setting it to null.

Is this the expected behavior? Is there a way to change it, so it would work like a relational database with the "on delete action" where you can set to "do nothing", "set null" or "cascade"?


Solution

  • Cascading deletes are not supported by Realm yet. There is an issue tracking it here as well as some proposed workarounds: https://github.com/realm/realm-java/issues/1104

    Just to have a solution here as well. Add your own custom "cascadeDelete" method that looks something like this:

    public class Foo extends RealmObject {
      public RealmList<Foo> list;
      public String name;
    
      public void cascadeDelete() {
        list.deleteAllFromRealm(); // The cascade part
        deleteFromRealm(); // delete this object
      }  
    }