Search code examples
javaandroiddatabaserealmrealm-mobile-platform

How to perform RealmQuery for two conditions


I'm trying to get an object from a list but with two specific conditions.

Here's the models

Class Car extends RealmObject{
    int id;
    RealmList<Model> models;
    /*
    other .. 
     */
}

Class Model extends RealmObject{
    int id;
     /*
    other .. 
     */
}

I get all the cars like this

RealmResults<Product> cars = realm.where(Car.class).findAll();

When I'm trying to get a specific car that has NO models.. I do this.

Car theCar = realm.where(Car.class).equalTo("id", selectedCar.getId()).findFirst();

But now.. I want to get a specific car that has a specific model ???

// this doesn't work
Car theCar = realm.where(Car.class).equalTo("id", selectedCar.getId())
                  .where(Model.class).equalTo("id", selectedModel.getId())
                  .findFirst();

Solution

  • You can use the link queries in realm

     Car theCar = realm.where(Car.class)
                           .equalTo("id", selectedCar.getId())
                           .equalTo("model.id", selectedModel.getId())                    
                          .findFirst();