简体   繁体   English

领域java查询条件

[英]Realm java query conditions

Assume the next situation: 假设下一个情况:

//I don't put the getters and setters, but assume they are there
public class User extends RealmObject {
    private RealmList<Dog> dogs;
}

public class Dog extends RealmObject {
    //UPDATE: I've added the variable city, to make my question more exact
    private String city;
    private String color;
    private String name;
}

Assume: Person 1 has dogs: NY-white-Joe Person 2 has dogs: NY-brown-Mary, SF-white-Fluffy, LA-brown-Fluffy Person 3 has dogs: NY-brown-Fluffy, LA-white-Pepito 假设:人1有狗:NY-white-Joe Person 2有狗:NY-brown-Mary,SF-white-Fluffy,LA-brown-Fluffy Person 3有狗:NY-brown-Fluffy,LA-white-Pepito

Question: How can I query all the persons that have a brown dog called Fluffy? 问题:如何查询所有有棕色狗叫蓬松的人?

What I have tried using the implicit AND: 我尝试使用隐式AND:

RealmQuery<User> userQuery = realm.where(User.class).equalTo("dogs.color", "brown").equalTo("dogs.name", "Fluffy");

Then I have read the documentation and the two equalTo() conditions are evaluated separately, that means that I will have: 然后我阅读了文档并分别评估了两个equalTo()条件,这意味着我将:

All the users that have a brown dog AND a dog that is called Fluffy. 所有拥有棕色狗和狗的用户称为Fluffy。 (So the results are P2, P3). (所以结果是P2,P3)。

How should I write this query to apply the conditions to the same dog? 我应该如何编写此查询以将条件应用于同一只狗?

It seems to me the best approach is to use query by primary key. 在我看来,最好的方法是使用主键查询。 I mean first adding primary key to Dog class: 我的意思是首先向Dog类添加主键:

class Dog extends RealmObject {
       @PrimaryKey
       private int id;
       private String color;
       private String name;
}

Then first step to find users that have a brown dog called Fluffy, is to find primary key of such a dog. 然后第一步找到有一只名叫Fluffy的棕色狗的用户,就是找到这种狗的主键。 So we making a query to find exact Dog : 所以我们进行查询以找到确切的Dog

Dog dog = realm.where(Dog.class).equalTo("color", "brown").equalTo("name", "Fluffy").findFirst();

After that we are searching for users that have a dog with defined primary key (id field): 之后,我们正在搜索具有已定义主键(id字段)的狗的用户:

RealmResults<User> users = realm.where(User.class).equalTo("dogs.id", dog.getId()).findAll();

The link queries in Realm are existential quantifiers ( https://en.wikipedia.org/wiki/Existential_quantification ). Realm中的链接查询是存在量词( https://en.wikipedia.org/wiki/Existential_quantification )。 That implies that if a condition is fulfil for just one object in the child class, the object in the parent class is added to the RealmResults . 这意味着如果条件仅满足子类中的一个对象,则父类中的对象将添加到RealmResults

Link query example shows how the existential quantifiers will work. 链接查询示例显示了存在量词的工作方式。 Currently, you will have to iterate User s and query the Dogs list individually. 目前,您必须迭代User并单独查询Dogs列表。

There is an open issue on reverse lookups. 反向查找存在一个未解决的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM