如何在Realm中获取父对象

时间:2021-03-06 16:45:19

Reference to realms doc

参考领域doc

I have some entities, for example it is: Category and Item.
The Category contains RealmList of Items and I can access all items of category by calling getter of this list.
But how can I query all items by category's id(it's annotated as primary key)
I'm parsing json via Realm.createObjectFromJson() and can't set Category field to each Item
Thanx in advance

我有一些实体,例如:类别和项目。类别包含项目的RealmList,我可以通过调用此列表的getter来访问所有类别的项目。但是如何通过类别的id查询所有项目(它被注释为主键)我正在通过Realm.createObjectFromJson()解析json,并且无法提前为每个项目Thanx设置类别字段

1 个解决方案

#1


6  

If there isn't any link from your Item to your Category you cannot currently query Items based on the Category. The concept you are looking for is on our TODO and is called backlinks. You can follow progress on that here: https://github.com/realm/realm-java/issues/607

如果您的项目与类别之间没有任何链接,则您目前无法根据类别查询项目。您正在寻找的概念在我们的TODO上,被称为反向链接。您可以在此处关注进度:https://github.com/realm/realm-java/issues/607

The current workaround would be to manually create that link after you copied them to Realm:

当前的解决方法是在将链接复制到Realm后手动创建该链接:

realm.beginTransaction();
Category category = realm.createObjectFromJson(categoryJson);
for (Item item : category.getItems()) {
  item.setCategory(category);
}
realm.commitTransaction();

// Then you can do
realm.where(Item.class).equalTo("category.id", category.getId()).findAll();

#1


6  

If there isn't any link from your Item to your Category you cannot currently query Items based on the Category. The concept you are looking for is on our TODO and is called backlinks. You can follow progress on that here: https://github.com/realm/realm-java/issues/607

如果您的项目与类别之间没有任何链接,则您目前无法根据类别查询项目。您正在寻找的概念在我们的TODO上,被称为反向链接。您可以在此处关注进度:https://github.com/realm/realm-java/issues/607

The current workaround would be to manually create that link after you copied them to Realm:

当前的解决方法是在将链接复制到Realm后手动创建该链接:

realm.beginTransaction();
Category category = realm.createObjectFromJson(categoryJson);
for (Item item : category.getItems()) {
  item.setCategory(category);
}
realm.commitTransaction();

// Then you can do
realm.where(Item.class).equalTo("category.id", category.getId()).findAll();