Relationship in realms

import 'package:realm/realm.dart';

part 'schemas.g.dart';

@RealmModel()
class _ItemCategory {
 @MapTo('_id')
 @PrimaryKey()
 late ObjectId id;
 late String name;
 late String description;
 late bool isActive;
 @Backlink(#categories)
 late _ItemType? type;
   late List<_Item> categories;
}

@RealmModel()
class _ItemType {
 @MapTo('_id')
 @PrimaryKey()
 late ObjectId id;
 late String name;
 late String description;
 late bool isConsumable;
 late List<_ItemCategory> categories;
 late bool isActive;
}

@RealmModel()
class _Item {
 @MapTo('_id')
 @PrimaryKey()
 late ObjectId id;
 late String name;
 late String description;
 late bool isActive;
 @Backlink(#items)
 late _ItemCategory? type;
}

Requirements

  1. Item Category must belong to one Type of ItemType
  2. ItemType can link to a numbers of ItemCategory
  3. Item type must belong to one or more CategoryType
  4. CategoryType link to a number of Type

Can you please modify my code to meet my requirements

Hi @Health_Centre_ERP!
You have to design your model according to your needs. The model could be changed during the development it may require redesign.
You can follow our documentation and our tests to understand how the backlinks are used.
This code sample is taken from our tests. Please note that the @Backlink annotation is on an Iterable collection in order to achieve ToMany relations like OneToMany and ManyToMany.

@RealmModel()
class _Source {
  String name = 'source';
  _Target? oneTarget;
  List<_Target> manyTargets = [];
}

@RealmModel()
class _Target {
   String name = 'target';

  @Backlink(#oneTarget)
  late Iterable<_Source> oneToMany;

  @Backlink(#manyTargets)
  late Iterable<_Source> manyToMany;
}

Here in the documentation you can find additional explanations about Backlinks.

2 Likes