Assume the next situation:
//I don't put the getters and setters, but assume they are there
public class User extends RealmObject {
private RealmList<Dog> dogs;
}
public class Dog extends RealmObject {
//UPDATE: I've added the variable city, to make my question more exact
private String city;
private String color;
private String name;
}
Assume: Person 1 has dogs: NY-white-Joe Person 2 has dogs: NY-brown-Mary, SF-white-Fluffy, LA-brown-Fluffy Person 3 has dogs: NY-brown-Fluffy, LA-white-Pepito
Question: How can I query all the persons that have a brown dog called Fluffy?
What I have tried using the implicit AND:
RealmQuery<User> userQuery = realm.where(User.class).equalTo("dogs.color", "brown").equalTo("dogs.name", "Fluffy");
Then I have read the documentation and the two equalTo() conditions are evaluated separately, that means that I will have:
All the users that have a brown dog AND a dog that is called Fluffy. (So the results are P2, P3).
How should I write this query to apply the conditions to the same dog?
It seems to me the best approach is to use query by primary key. I mean first adding primary key to Dog
class:
class Dog extends RealmObject {
@PrimaryKey
private int id;
private String color;
private String name;
}
Then first step to find users that have a brown dog called Fluffy, is to find primary key of such a dog. So we making a query to find exact Dog
:
Dog dog = realm.where(Dog.class).equalTo("color", "brown").equalTo("name", "Fluffy").findFirst();
After that we are searching for users that have a dog with defined primary key (id field):
RealmResults<User> users = realm.where(User.class).equalTo("dogs.id", dog.getId()).findAll();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With