简体   繁体   中英

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)

I would like to query a list of all Kid s belonging to Father , without querying Father itself, via:

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 .

Do I have to query the Father object and then call the getKids() method?

If you're wondering why I'm not simply querying Father : I have a generic method for querying, querying any class given to it:

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. 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 .

For your case, you have to use the conventional method of design the ER for the database.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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