我有 2 个实体 User 和 Location,它们之间有“多对多”关系。创建关系似乎可行,但删除则不行。目的不是删除实体,而是删除关系。
我有 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>();
}
一种方法来更新位置和用户之间的关系。用户是该位置的用户列表(由 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;
}