I’m developing a social networking app and encountering a persistence issue with friend relationships. Through debugging, I discovered that each user can only be a friend to one other user, meaning two users cannot share a mutual friend. I’m unsure how to handle this many-to-many relationship in SwiftData and would greatly appreciate any assistance. Thank you in advance. Here is my relative code:
@Model
class User: Identifiable {
@Relationship var Friend: Array<User>
}
if !userInfo[index].Friend.contains(userInfo[indexpre]) {
userInfo[index].Friend.append(userInfo[indexpre])
userInfo[indexpre].Friend.append(userInfo[index])
do {
try context.save()
print("成功保存")
} catch {
// 处理保存失败的情况
print("保存消息时出错: \(error)")
}
}