Skip to content

Instantly share code, notes, and snippets.

@bapspatil
Created February 13, 2018 11:45
Show Gist options
  • Save bapspatil/ec5fbd5a639c377ea5c0c84c1c991f8b to your computer and use it in GitHub Desktop.
Save bapspatil/ec5fbd5a639c377ea5c0c84c1c991f8b to your computer and use it in GitHub Desktop.
How to work with inverse relationships in Realm
public class Dog extends RealmObject {
@PrimaryKey private String id;
private int age;
@LinkingObjects("dogs") // <-- !
private final RealmResults<Person> owners = null; // <-- !
// getters, setters
}
public class Person extends RealmObject {
@PrimaryKey private String id;
private String name;
private RealmList<Dog> dogs;
// getters, setters
}
// Creating objects
mRealm.executeTransaction((realm) -> {
Dog dog = realm.createObject(Dog.class, "dogId");
Person person = realm.createObject(Person.class, "personId");
person.getDogs().add(dog);
// dog.getOwners() will automatically contain `person`
});
// Link query
RealmResults<Dog> dogs = mRealm.where(Dog.class)
.equalTo("owners.name", "Taylor")
.findAll();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment