0

I'll explain my question using USER -> TASK (1-user-can-have-many-tasks) as an example.

In realm, I can define the USER ENTITY, which includes in it a list of associated tasks.

However, when querying all users, I also want to read as part of user list, a set of attributes for each user that are summaries of an equivalent attributes on the tasks for this user.

For example, I want to read all users, and for each user, report 'Outstanding' if any of the linked tasks are outstanding. report 'Has Attachment' for a user, if ANY of the tasks for that user have attachments.

In plain SQL with SQLLite, I can achieve this effect using groupby constructs and deriving columns in my resultset that are summaries of real columns.

How can I accomplish the same in Realm. Any help is appreciated.

Example Entity:

User
{
  String userId
  String name
  List<Task> tasks
  **--> oustanding** (need to derive if any of the tasks in the task list is outstanding)
  **--> hasAttachments** (if any of the tasks in the task list has 
attachments)
}

Task
{ 
    String taskId
    boolean outstanding
    boolean hasAttachments
}

Note: outstanding and hasAttachments on the User entity are not defined fields necessary. I just need to derive them at runtime, in query or as dynamic fields, if there is such a thing

1 Answers1

0

Good news is that Realm supports "link queries" which technically translate to "has at least one of where X is true", which is exactly what you are looking for:

realm.where(User.class).equalTo("tasks.outstanding", true).findAll(); // users with at least 1 outstanding task

realm.where(User.class).equalTo("tasks.hasAttachments", true).findAll(); // users with at least 1 task that has attachments
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • Hi @EpicPandaForce - thanks for responding. You have provided a good answer however my use case is not to retrieve a last of users that have their talk in a given status. Rather my use case is to get a list of all users, and for each user, have an attribute called is outstanding if any of the tasks have outstanding flag on. It's essentially a boolean attribute that us a summary of boolean attributes over the task lists for each user. – Waqas Ahmed May 11 '18 at 23:06
  • Well if you have to have it as a boolean field for some reason, then you gotta have to manage that yourself. Linking objects might help. – EpicPandaForce May 12 '18 at 00:49