Created
February 13, 2018 11:45
-
-
Save bapspatil/ec5fbd5a639c377ea5c0c84c1c991f8b to your computer and use it in GitHub Desktop.
How to work with inverse relationships in Realm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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