A Kingdom Request with Two Conditions at the Same Time

How to request such a structure:

public class Animal extends RealmObject { 
    RealmList<Bird> birds;
}


public class Bird extends RealmObject { 
    int type;
    RealmList<RealmInteger> species;
}

RealmInteger is an object with int value

I want to find all Animalobjects with Birdthat have the form value3 AND, which Birdmatters type2

I tried this, but it ignores type:

realm.where(Animal.class)
    .equalTo("birds.type", 2)
    .equalTo("birds.species.value", 3)
    .findAll();

I assume that it matches the value, but does not check the type field at the same time. Do I need to do .equalTo("birds.species.value", 3)to check only "Birds" type2?

Update : I tried @EpicPandaForce answer below, it also returns this Animal with data:

"birds": [
     {
        "species": [3, 15, 26],
        "type": 1
     },
     {
        "species": [],
        "type": 2,
     }
]

Since this one Animaldoes not have the form of valueof 3 (empty) type2, it should NOT return it. However, this is happening.

+4
2

, , , , .

, Animal RealmList. , , - , Realm. , , : https://realm.io/docs/java/latest/#link-queries. .

, - , , @LinkingObjects + . :

// Animal class must have a stable hashcode. I did it by adding a primary key
// here, but it can be done in multiple ways.
public class Animal extends RealmObject {
    @PrimaryKey
    public String id = UUID.randomUUID().toString();
    public RealmList<Bird> birds;

    @Override
    public boolean equals(Object o) {
        // Make sure you have a stable equals/hashcode
        // See https://realm.io/docs/java/latest/#realmobjects-hashcode
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Animal animal = (Animal) o;
        return id.equals(animal.id);
    }

    @Override
    public int hashCode() {
        return id.hashCode();
    }
}

// Add a @LinkingObjects field to Bird
// See https://realm.io/docs/java/latest/#inverse-relationships
public class Bird extends RealmObject {
    public int type;
    public RealmList<RealmInteger> species;
    @LinkingObjects("birds")
    public final RealmResults<Animal> animalGroup = null;

    @Override
    public String toString() {
        return "Bird{" +
                "type=" + type +
                '}';
    }
}

// Query the birds instead of Animal
RealmResults<Bird> birds = realm.where(Bird.class)
        .equalTo("type", 2)
        .equalTo("species.value", 3)
        .findAll();

// You must collect all Animals manually
// See https://github.com/realm/realm-java/issues/2232
Set<Animal> animals = new HashSet<>();
for (Bird bird : birds) {
    animals.addAll(bird.animalGroup);
}
+2
realm.where(Animal.class)
  .equalTo("birds.type", 2)
  .findAll()
  .where()
  .equalTo("birds.species.value", 3)
  .findAll();

.

+1

Source: https://habr.com/ru/post/1683089/


All Articles