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.
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 .
Your problem is that you are querying based on TodoList
when you actually want to query Task
s.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With