flutterobjectboxflutter-objectbox

Flutter ObjectBox Save nested ToOne ToMany Entities


I have the following entities:

@Entity()
class CategoryData {
  CategoryData({
    this.id = 0,
    required this.catName,
  });

  @Id()
  int id;
  String catName;

  @Backlink()
  final subCats = ToMany<SubCatData>();
}

@Entity()
class SubCatData {
  SubCatData({
    this.id = 0,
    required this.subCatPair,
  });

  @Id()
  int id;
  String subCatPair;

  @Backlink()
  final groups = ToMany<GroupData>();
  final catData = ToOne<CategoryData>();
}

@Entity()
class GroupData {
  GroupData({
    this.id = 0,
    required this.groupPair,
  });

  @Id()
  int id;
  String groupPair;

  @Backlink()
  final groups = ToMany<Item>();
  final subCatData = ToOne<SubCatData>();
}

@Entity()
class Item {
  const Item({this.id = 0});
  @Id()
  int id;
}

My goal is to save instances of each of these entities under 2 separate CategoryData boxes:

My question is: Do I need to create a box for each entity twice (one for box1, and the other for box2)?

// saving the 1's and 2's in 2 different stores:
late final Store store1;
late final Store store2;

late final Box<CategoryData> box1;
late final Box<SubCatData> boxsubCat1;
late final Box<GroupData> boxGroup1;
late final Box<Item> boxItems1;

late final Box<CategoryData> box2;
late final Box<SubCatData> boxsubCat2;
late final Box<GroupData> boxGroup2;
late final Box<Item> boxItems2;

This seems really messy and inefficient to maintain, there surely exists a better alternative!

Which kind of structure would you use to achieve this result?

Thanks!


Solution

  • In ObjectBox you can only have one Box for an @Entity.

    Two suggestions for this: