Im trying to delete users who are not in a given array and have only one groupid associated with them. Users can have multiple group ids. Its a one to many relation.
For example lets say the database has users [1, 2, 3, 4] user 3 is associated with group 1 and user 4 is associated with group 1 and 2
Now if have an array of users = [1, 2] and we want to delete users that are not in this array and are only part of group_id 1
The result should be to delete user 3 and not delete user 4 since 4 is also associated with another group
This is the query I wrote but this also deleted users who have multiple groups . Is there a way to say ONLY group.id = %@
let ids = users.map({ $0.uid })
let predicate = NSPredicate(format: "NOT (id in %@) && ANY group.id = %@", ids, groupId)
persistenceManager.delete(predicate, User.self)
CodePudding user response:
You can check the number of entries in a to-many relationship with @count
, so the predicate should be
NSPredicate(format: "NOT (uid in %@) && ANY group.id = %@ && group.@count = 1",
ids, groupId)