Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Realm Query Relationship

Tags:

android

realm

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.

like image 382
Val Okafor Avatar asked Mar 13 '23 21:03

Val Okafor


2 Answers

With backlink query this would be much easier, but unfortunately it has not been implemented yet (Mar. 18th, 2016), see http://github.com/realm/realm-java/issues/607 .

The both approaches are fine. you can actually convert a RealmList to RealmResults by realmList.where().findAll() .

The other better abstract object RealmCollection will be added recently to support this use case better, see http://github.com/realm/realm-java/pull/2345 .

like image 126
beeender Avatar answered Mar 15 '23 10:03

beeender


Your problem is that you are querying based on TodoList when you actually want to query Tasks.

The simple solution to this problem is to have the id of the parent also within the child.

public class Task extends RealmObject {
    @PrimaryKey
    private int id;
    private String title; 
    private boolean completed;
    private TodoList todoList;        
    private int todoListId;
    ...
}

Then you can do

public RealmResults<Task> getTodoListTasks2(TodoList list) {
    return mRealm.where(Task.class).equalTo("todoListId", list.getId()).findAll();
}
like image 25
EpicPandaForce Avatar answered Mar 15 '23 11:03

EpicPandaForce