领域同时查询两个条件

ono*_*ono 8 android realm

我如何查询这样的结构:

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


public class Bird extends RealmObject { 
    int type;
    RealmList<RealmInteger> species;
}
Run Code Online (Sandbox Code Playgroud)

RealmInteger是一个带有的对象 int value

我想找到所有物种为3 AND 且为2的Animal物体BirdvalueBirdtype

我尝试了这个,但它一直忽略了type:

realm.where(Animal.class)
    .equalTo("birds.type", 2)
    .equalTo("birds.species.value", 3)
    .findAll();
Run Code Online (Sandbox Code Playgroud)

我的猜测是它找到了与值匹配但不同时检查类型字段.我需要一种方法.equalTo("birds.species.value", 3)来检查只有type2的鸟?

更新:尝试下面的@EpicPandaForce答案,它也返回这个动物的数据:

"birds": [
     {
        "species": [3, 15, 26],
        "type": 1
     },
     {
        "species": [],
        "type": 2,
     }
]
Run Code Online (Sandbox Code Playgroud)

因为Animal它没有value3 的物种(它是空的)type2,它不应该返回它.它确实如此.

Chr*_*ior 5

不幸的是,您遇到了链接查询工作方式的特殊性,目前,没有简单的方法可以做您想做的事。

根本原因是您从 的角度进行查询,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);
}
Run Code Online (Sandbox Code Playgroud)