Search code examples
androidrealm

Realm nested query [Android]


I have a rather simple problem but can't seem to find the answer. I have 3 realm objects - Month, Day and Goal. Month contains list of Days and each Day contains list of Goals. This is simplified version:

class Month extends RealmObject {
    RealmList<Day> days;
}

class Day extends RealmObject {
    RealmList<Goal> goals;
}

class Goal extends RealmObject {
    //some data
}

How can I query for Goals that belong to specific Month?

That is - I can get list of Days for specific Month, but now from that list of Days I need to pull out all the Goals they contain, and by using a query. Thanks.


Solution

  • You can make use of inverse relationships:

    The models will look like:

    class Month extends RealmObject {
        String name;
        RealmList<Day> days; 
    }
    
    class Day extends RealmObject {
        String name;
        RealmList<Goal> goals; 
    
        @LinkingObjects("days")
        final RealmResults<Month> month = null;
    }
    
    class Goal extends RealmObject {
        String name;
    
        @LinkingObjects("goals")
        final RealmResults<Day> day = null;
    }
    

    And the query will be as simple as:

    RealmResults<Goal> = realm
        .where(Goal.class)
        .equalTo("day.month.name", "august")
        .findAll();
    

    If you have 100 months, each having 100 days, each having 100 goals (1 million goals total), your query will be executed in about 300 ms with Realm and in about 900ms with OrmLite (SQLite ORM). I tested this on OnePlus 3T.