Realm Custom Request Terms

Suppose the following 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; } 

Suppose: 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 request all people who have a brown dog called Fluffy?

What I tried using implicit AND:

 RealmQuery<User> userQuery = realm.where(User.class).equalTo("dogs.color", "brown").equalTo("dogs.name", "Fluffy"); 

Then I read the documentation, and two equalTo () conditions are evaluated separately, which means I will have:

All users who have a brown dog AND a dog called Fluffy. (Thus, the results are P2, P3).

How do I write this query to apply conditions to the same dog?

+5
source share
2 answers

I think the best approach is to use a primary key query. I mean adding the primary key to the Dog class first:

 class Dog extends RealmObject { @PrimaryKey private int id; private String color; private String name; } 

Then, the first step to find users who have a brown dog called "Fluffy" is to find the primary key of such a dog. Therefore, we make a request to find the exact Dog :

 Dog dog = realm.where(Dog.class).equalTo("color", "brown").equalTo("name", "Fluffy").findFirst(); 

After that, we look for users who have a dog with a specific primary key (id field):

 RealmResults<User> users = realm.where(User.class).equalTo("dogs.id", dog.getId()).findAll(); 
+1
source

Link requests in Realm are existence quantifiers ( https://en.wikipedia.org/wiki/Existential_quantification ). This means that if the condition is RealmResults for only one object in the child class, the object in the parent class is added to RealmResults .

An example link request shows how existence quantifiers will work. Currently, you will have to iterate over User and query the Dogs list individually.

There is an open issue in the reverse search.

+1
source

Source: https://habr.com/ru/post/1232075/


All Articles