Check if a RealmObject have any relationship when deleting (Similar to FK constraint)


#1

Hi!

Take this example:

public class Person extends RealmObject {
  private String id;
  private String name;
  private RealmList<Dog> dogs;
  // getters and setters
}

public class Dog extends RealmObject {
  private String id;
  private String name;
  private String color;
  @LinkingObjects("dogs")
  private final RealmResults<Person> owners;
  // getters and setters
}

is there anyway to make deleting auto check if this Person object are used by any Dog object? Currently I can just delete the Person object right away, and the Dog object will became an orphan object.

For now, I’m checking each of the relationship manually (eg. checking if Person.dogs.any();), it became very hard to write when I have a lot of linking, any idea?


#2

Unfortunately, Realm doesn’t support cascade delete - so you need to implement manually.

We are using Repositories for the DB operations (each model has its own repository), so there is a custom delete function. We can check there so you don’t need to repeat all the things.


#3

Can I know roughly how does your custom delete function looks like? Do you have a Generic function for that?


#4

It’s not generic, completely custom. There are a few helper methods/frameworks on github if you are looking for that. Search for realm cascade delete.

UserRepo.deleteUser(with: userID) {
     let user = getUser(from: userID)

     if user.settings != nil {
     	SettingsRepo.deleteSettings(user.settings) 
     }

     if user.exercises.count > 0 {
        for let exercise on user.exercise {
        	ExerciseRepo.delete(exercise)
        }
     }

     ...
}

like this: https://github.com/PoissonBallon/EasyRealm