Home Ask Login Register

Developers Planet

Your answer is one click away!

gonzalomelov February 2016

Realm Android Nested Query

Given the below classes and relationships, I need a RealmResults < Model1 > that satisfies the following requirements:


int id


int id
int model1Fk
int type


int model2Fk

I want to query all the Model1 entities that, for a specific Model2 related instance type, that Model2 instance has at least one Model3 related instance.

In SQL that would be (Haven't tested it):

select distinct model1.*
from Model1 model1 join Model2 model2 on model2.model1Fk = model1.id join Model3 model3 on model3.model2Fk = model2.id
where model2.type = 'Some Type'


greenrobo February 2016

Are these models stored in a SQLite database in Android or are they plain Java objects?

If they are native objects, then you could have a reference to those directly. e.g.

class Model1 {
   int id;
   RealmList<Model2> list;
class Model2 {
   int id;
   int type;
   Model1 parent;


You could even build a hashmap that will do all this for you. Depending on how these objects exist in Android one can come up with a strategy.

Christian Melchior February 2016

Your text description and join doesn't match, but if you want to find all Model1 with a Model2 of Some type, you can do the following:

realm.where(Model1.class).equalTo("model2List.type", "Some Type").findAll();

You can read about link queries here: https://realm.io/docs/java/latest/#link-queries.

If you want to find all Model1 which have at least 1 Model2 that also have at least one Model3 with some value, you can do the following:

realm.where(Model1.class).equalTo("model2List.Model3List.model2Fk", "some model2Fk value").findAll();

Post Status

Asked in February 2016
Viewed 3,440 times
Voted 5
Answered 2 times


Leave an answer

Quote of the day: live life