Kim Montano
Kim Montano

Reputation: 2285

Find all child realm objects where the parent's id is X

In this example, the docs talked about getting the parent objects while specifying queries for the child objects.

Is there a way for getting the child objects while specifying a query for the parent object?

In the given example, can I search for dogs who are of brown color with the user named John?

enter image description here

Upvotes: 2

Views: 2685

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81539

EDIT: Since Realm 3.5.0, you can actually use the "backlinks" mentioned in the comment section. Rejoice!

In fact, since Realm 3.0.0, bidirectional links are a performance bottleneck, so using backlinks is the preferred way.

The way it works is:

public class User extends RealmObject {
    private RealmList<Dog> dogs;
}

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

Now you can do:

realm.where(Dog.class).equalTo("color", "Brown").equalTo("owners.name", "John").findAll();

OLD ANSWER:

You can only search for dogs with a given user if you have an object link to the User.

public class Dog extends RealmObject {
    //...
    private User user;
}

Then you could do

realm.where(Dog.class).equalTo("color", "Brown").equalTo("user.name", "John").findAll();

Upvotes: 4

Related Questions