Android Realm Query Relationship

Viewed 2930

I have a Realm Object called TodoList which has a property of RealmList like this.

   @PrimaryKey
    private int id;
    private String title;    
    private RealmList<Task> tasks;

And I here the Task Realm object

   @PrimaryKey
    private int id;
    private String title; 
    private boolean completed;
    private TodoList todoList;

My question what is the best way to write a Realm query that returns that list of Tasks that belong to a particular TodoList. Here is my approach.

public RealmResults<Task> getTodoListTasks(int todoListId) {
        RealmResults<Task> tasks = mRealm.where(Task.class)
                .equalTo("todoList.id", todoListId).findAll();
        return tasks;
}

This approach requires that I query the Task table looking for all the TodoList foreign keys that matches a given id. I was hopping for something like this:

 public RealmResults<Task> getTodoListTasks2(TodoList list) {
        TodoList todoList =  mRealm.where(TodoList.class).equalTo("id", list.getId()).findFirst();
        RealmResults<Task> tasks = todoList.getTasks();
        return tasks;

    }

However this will not build because I cannot cast RealmList to RealmResult.

2 Answers
Related