justinraczak
justinraczak

Reputation: 786

How to query for Realm objects related to multiple other Realm objects in Realm Java

When I try to query for object relationship by passing the object in the equalTo query, the IDE complains that the comparison cannot be made. What is the correct way to query for Realm objects related to each other? My relationships are set up like this:

public class Workout extends RealmObject implements Parcelable {

    @PrimaryKey
    private String id;
    @Required
    private String name;
    public RealmList<Set> sets;
    public RealmList<Exercise> exercises;
    private Date date;

public class Set extends RealmObject implements Parcelable {

    @PrimaryKey
    private String id;
    @Required
    private Date date;
    private Workout workout;
    private Exercise exercise;
    private int reps;
    private float weight;

Upvotes: 0

Views: 905

Answers (1)

justinraczak
justinraczak

Reputation: 786

In my case, I have one object (a Workout) which has one or more sets and exercises related to it. A set is related to an exercise and a workout. To count the sets of a given exercise within a given workout, I need to find all sets which are related to the exercise and the workout. This can be accomplished by using any unique field for the desired objects and a dot access notation.

For example:

results = realm.where(Set.class).equalTo("workout.id", this.getId())
                .equalTo("exercise.id", exercise.getId())
                .findAll();

Here I use the UUID created for each of the objects and compare that rather than the object itself. This works until abstract direct object comparison is implemented in Realm.

Upvotes: 1

Related Questions