Hello,
I'm using Realm 3.1.0 for persistence, and I came across a problem regarding fetching recursive nested objects. Below is a Category class example:
open class Category : RealmObject() {
@PrimaryKey
open var id: Int = 0
open var name:String? = ""
open var child_categories: RealmList<Category>? = null
}
After generating the Category hierarchy I persist like this:
realm.beginTransaction()
realm.copyToRealm(categories)
realm.commitTransaction()
where "categories" is a list of the high-level categories, with all their child categories. This persist all data. The problem is querying Realm to return only the high-level categories, but if do a findAll(), it returns all categories regardless of level.
Do I need to model the Category class differently, adding a "level" field? I would like to avoid that..
Thanks in advance,
Jo茫o
Hi @joaocruz04
If you do something like where(Category.class).findAll() it will find all categories no matter where they are. If you only want categories at the "bottom", you could do something like:
where(Category.class).isEmpty("child_categories").findAll()
If you have 3 levels it would be impossible to tell the difference between level 1 and 2, since they would both have data in their child_categories list, so in that case there is no other way than adding a depth field or something like that.
well you COULD model it as
open class Category : RealmObject() {
@PrimaryKey
open var id: Int = 0
open var name:String? = ""
open var parent_category: Category? = null
open var child_categories: RealmList<Category>? = null
}
and top level means realm.where(Category.class).isNull("parent_category"):
So it seems I should change the model a bit. Thank you guys for the replies!
@joaocruz04 I've had to do this before 馃槃
public class FeedCategory
extends RealmObject {
@PrimaryKey
private long id;
private int rank;
private String title;
@Index
private String titleLowercase;
private String color;
private String subcategoryColor;
private String icon;
private RealmList<FeedCategory> subcategories;
private FeedCategory parent;
```
and
``` java
public class FeedCategoryRepositoryImpl
extends LongRealmRepositoryImpl<FeedCategory>
implements FeedCategoryRepository {
@Override
public RealmResults<FeedCategory> findAllParentCategories(Realm realm) {
return query(realm).isNull(FeedCategoryFields.PARENT).findAllSorted(FeedCategoryFields.RANK);
}
Most helpful comment
well you COULD model it as
and top level means
realm.where(Category.class).isNull("parent_category"):