user274051
user274051

Reputation: 325

How do I obtain all the realmObjects from a realmList which is within another realmList?

sorry if the question is not very clear. Let me try to develop on that here. This is my structure.

public class User extends RealmObject{
  ...
  RealmList<Tags> userTags;
}

public class Tags extends RealmObject{
  ...
  RealmList<Results> tagResults;
}

public class Results extends RealmObject{
  ...
}

In one of my activities, I want to obtain all the Tags and all the containing Results from a specific User. For example:

user1 -> tag1 -> result1
              -> result2
      -> tag2 -> result3
              -> result4

The desired result should be result1, result2, result3, result4.

Right now I am doing it manually

...
RealmList<Results> tagResults = new RealmList<>;
RealmList<Tags> userTags= user1.getTags();
for (Tags tag : userTags)
{
  tagResults.addAll(tag.getResults());
}
mRealmAdapter = new RealmResultsAdapter(this, tagResults);

Is there any other way to obtain the desired result without doing it manually?

Thanks in advance

Upvotes: 1

Views: 685

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81539

EDIT: Realm 3.5.0 added inverse relationships, so you should do this:

public class User extends RealmObject{
  ...
  RealmList<Tags> userTags;
}

public class Tags extends RealmObject{
  ...
  @LinkingObjects("userTags")
  private final RealmResults<User> tagOfUsers = null;

  RealmList<Results> tagResults;
}

public class Results extends RealmObject{
  @LinkingObjects("tagResults")
  private final RealmResults<Tags> resultsOfTags = null;

  ...
}

And

RealmResults<Tags> tags = realm.where(Tags.class).equalTo("tagOfUsers.userId", userId).findAll(); // has results

PRE-3.0.0 ANSWER:

Due to that we're still waiting on inverse relationships (backlinks), I'd set up the RealmObjects like this

public class User extends RealmObject{
  ...
  @PrimaryKey
  long id;

  RealmList<Tags> userTags;
}

public class Tags extends RealmObject{
  ...
  @PrimaryKey 
  long id; 

  User user;

  @Index
  long userId;

  RealmList<Results> tagResults;
}

public class Results extends RealmObject {
  User user;

  @Index
  long userId;

  Tags tag;

  @Index
  long tagId;
  ...
}

Then

RealmResults<Results> results = realm.where(Results.class).equalTo("userId", userId).findAll();

Upvotes: 3

Related Questions