为什么objectbox-dart中不允许多对一反向链接?

问题描述

我有这个结构:

@JsonSerializable()
class Media {
  @Id(assignable: true)
  int id = 0;
  int lid = 0;
  String url = '';
  String? title;
}

@Entity()
class NewsPicture extends Media {
  @override
  @Id(assignable: true)
  int id = 0;

  @Backlink('newsPicture')
  final news = ToOne<News>();
}

@JsonSerializable(explicitToJson: true)
@Entity()
class News extends Data<News> implements DataInterface<News> {
  @Id(assignable: true)
  @JsonKey(defaultValue: 0)
  int lid = 0;
  final Picture = ToMany<NewsPicture>();
}

生成过程中,objectBox_generator:resolver 给了我这个错误信息:

@Backlink() 注释的无效使用 - 只能用于 ToMany 字段

为什么不允许?我错过了什么?

解决方法

它在那个方向不受支持,因为它不是真正需要的(对任何事情都没有帮助),您只需翻转方向/更改存储关系的位置即可。此外,ToOne 关系的存储效率更高,因为它们只是数据库中的单个字段,而独立的 ToMany 关系需要一个中间“映射表”。

如果你像这样更新你的模型,它就会起作用,你不会看到在你的应用程序中使用它的方式有什么不同:

@Entity()
class NewsPicture extends Media {
  @override
  @Id(assignable: true)
  int id = 0;

  final news = ToOne<News>();
}

@JsonSerializable(explicitToJson: true)
@Entity()
class News extends Data<News> implements DataInterface<News> {
  @Id(assignable: true)
  @JsonKey(defaultValue: 0)
  int lid = 0;

  @Backlink()
  final Picture = ToMany<NewsPicture>();
}