简体   繁体   English

领域:如何仅查询一对多关系中父亲的对象

[英]Realm: How to query only the objects of a father in a one-to-many relationship

I have the following problem: 我有以下问题:

Father containing a RealmList<Kid> (with Kid being another RealmObject) Father包含一个RealmList<Kid>Kid是另一个RealmObject)

I would like to query a list of all Kid s belonging to Father , without querying Father itself, via: 我想通过以下方式查询属于Father的所有Kid的列表,而不查询Father本身:

Realm.getDefaultInstance().where(Kid.class).equalTo("fatherId", id);

But I'm pretty certain that this is not possible, as Kid has no reference to Father . 但是我可以肯定这是不可能的,因为Kid没有提到Father

Do I have to query the Father object and then call the getKids() method? 我是否必须查询Father对象,然后调用getKids()方法?

If you're wondering why I'm not simply querying Father : I have a generic method for querying, querying any class given to it: 如果您想知道为什么我不只是查询Father :我有一个通用的查询方法,查询给定的任何类:

public <T extends RealmObject> List<T> getForFather(Class<T> clazz, String fatherId)

Most of the classes queried belong to Father and I want to avoid if-else statements. 所查询的大多数类都属于Father ,我想避免使用if-else语句。 I also would like to avoid multiple methods doing the same thing, just with another class. 我还想避免使用另一个类的多个方法做同样的事情。 Above generic method would work, but only, if there's a way to query Kid for a specific Father . 上面的通用方法是可行的,但只有在有一种方法可以向Kid查询特定的Father时才有效。

For your case, you have to use the conventional method of design the ER for the database. 对于您的情况,您必须使用为数据库设计ER的常规方法。

That is, Instead of having RealmList<Kid> in your father object create a primaryKey in the father and have the reference of that primary key in child fatherPrimaryKey 这是不是具有, RealmList<Kid>在你father的对象创建primaryKeyfather ,并在孩子该主键的参考fatherPrimaryKey

then you can simply query 然后您只需查询

RealmResults<Kid> result = realm.where(Kid.class).equals("fatherPrimaryKey", "some_key").findAll();

And while storing the data in the kid object, make sure you pass the correct value of father's primary key to the child as reference. 并且在将数据存储在kid对象中时,请确保将father's primary key的正确值传递给孩子作为参考。

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

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