implementing simple one-to-one and one-to-many relationship

47 Views Asked by At

i have this database schema for my application and i think this schema is correct but i can't add multiple item with one-to-many relationship, in the first time i can add one user with one group and config, but i can't add multiple group to one user and multiple config to one group

User can have many Group and each Group belongs to one User

Group can have many Config and each Config belongs to one Group

and i can have many User in application

USER collection:

@collection
class UserCollection {
  Id id = Isar.autoIncrement;
  late String username = '';
  late String password = '';
  final group = IsarLinks<GroupCollection>();
}

GROUP collection:

@collection
class GroupCollection {
  Id id = Isar.autoIncrement;

  final IsarLinks<ConfigCollection> config = IsarLinks<ConfigCollection>();

  @Backlink(to: 'group')
  final user = IsarLinks<UserCollection>();

  late String label;
}

CONFIG collection:

@collection
class ConfigCollection {
  Id id = Isar.autoIncrement;
  late String remark;

  late String link;

  @Backlink(to: 'config')
  final group = IsarLinks<GroupCollection>();
}

now i want to create new data into database

void testSaveDatabase() async{
  final isar = IsarHelper.instance;

  const link =
     "LINK";


  final newConfig = ConfigCollection()
    ..remark = 'test'
    ..link = link

  final newGroup = GroupCollection()
    ..label = 'label'
    ..config.add(newConfig);

  await isar.isarInstance.writeTxn(() async {
    try{
      final user = isar.findLast<UserCollection>();

      await isar.isarInstance.configCollections.put(newConfig);
      await isar.isarInstance.groupCollections.put(newGroup);

      user!.group.add(newGroup);
      newGroup.config.add(newConfig);

      await newGroup.config.save();
      await user.group.save();

    }catch(error){
      print(error);
    }
  });
}
0

There are 0 best solutions below