通过多对多链接管理实体之间的关系

问题描述 投票:0回答:1

我有 2 个实体

User
Location
,带有多对多链接。建立关系似乎有效,但删除关系却无效。 目标不是“删除”实体,而是“仅删除关系”。 是否应该对两个实体进行删除? 只有带有@Backlink 的吗? 我尝试了几种基于

.remove()

+

put()

的解决方案,但没有成功。

@Entity()
class LocationModel {
  @Id()
  int localId = 0;

  @Unique(onConflict: ConflictStrategy.replace)
  int id;

  @Backlink('location')
  final items = ToMany<ItemModel>();

  final users = ToMany<UserModel>();
}


@Entity()
class UserModel {
  @Id()
  int localId = 0;

  @Unique(onConflict: ConflictStrategy.replace)
  String guid;

  @Backlink('user')
  final items = ToMany<ItemModel>();

  @Backlink()
  final locations = ToMany<LocationModel>();
}
有一种方法可以更新位置和用户之间的关系。 Users 是该位置的用户列表(由 API 给出)。目标是更新关系(并且仅更新关系)。

这个想法也将是使用用户集合中的方法执行类似的操作,以更新用户和位置列表。

LocationModel updateUsers( LocationModel locationModel, List<UserModel> users, ) { // Update users that may still have a link to this location final usersByLocation = userCollection.getByLocation(locationModel.localId); // Remove relationship with location if no users (users.isEmpty) or no longer present in users list final userToRemoveLocation = users.isEmpty ? usersByLocation : usersByLocation .where((user) => !users.any((u) => u.guid == user.guid)) .toList(); for (var user in userToRemoveLocation) { user.locations.remove(locationModel); userCollection.put(user); final locationInDb = locationBox.get(locationModel.localId); if (locationInDb != null) { locationInDb.users.remove(user); locationBox.put(locationInDb); } } // Creation of new relationships between location and users (users list) for (var user in users) { final userInDb = userCollection.getByServerId(user.guid); if (userInDb != null) { userInDb.locations.add(locationModel); userCollection.put(userInDb); final locationInDb = locationBox.get(locationModel.localId); if (locationInDb != null) { locationInDb.users.add(user); locationBox.put(locationInDb); } } } return locationModel; }

@Backlink
flutter objectbox flutter-objectbox
1个回答
0
投票
ToMany

注释只会以“反向”方向访问

@Backlink
所指向的关系。它实际上并没有创建另一种关系。
因此要更新关系,只需要“从任意一侧”完成即可。例如。这应该足够了:
for (var user in userToRemoveLocation) {
  user.locations.remove(locationModel);
  userCollection.put(user);

  // final locationInDb = locationBox.get(locationModel.localId);
  // if (locationInDb != null) {
  //   locationInDb.users.remove(user);
  //   locationBox.put(locationInDb);
  // }
}

https://docs.objectbox.io/relations#access-many-to-many-in-the-reverse-direction

    

© www.soinside.com 2019 - 2024. All rights reserved.