Borzh
Borzh

Reputation: 5205

Android Realm query inverse relationship

Using Person -> Dogs example from Realm documentation, how do I obtain all Dogs without owner?

class Person extends RealmObject {
    // ...
    private RealmList<Dog> dogs;
}

class Dog extends RealmObject {
    // ...
    @LinkingObjects("dogs")
    private final RealmResults<Person> owners = null;
}

Upvotes: 1

Views: 289

Answers (1)

Ken Li
Ken Li

Reputation: 98

According to the tutorial here Queries, you can query the record in Realm DB like this

// Build the query looking at all users:
RealmQuery<User> query = realm.where(User.class);

// Add query conditions:
query.equalTo("name", "John");
query.or().equalTo("name", "Peter");

// Execute the query:
RealmResults<User> result1 = query.findAll();

// Or alternatively do the same all at once (the "Fluent interface"):
RealmResults<User> result2 = realm.where(User.class)
                                  .equalTo("name", "John")
                                  .or()
                                  .equalTo("name", "Peter")
                                  .findAll();

You can either loop through result 1 to find Dogs with empty owners or set the query to find dogs with empty owners.

Like this for example:

RealmResults<User> result2 = realm.where(Dog.class)
                                  .isNotEmpty("owners")
                                  .findAll();

Upvotes: 1

Related Questions