核心数据删除规则和多对多关系 [英] Core Data Deletion rules and many-to-many relationships

查看:104
本文介绍了核心数据删除规则和多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有部门和员工,每个部门有多个员工,但每个员工也可以是多个部门的一部分。

Say you have departments and employees and each department has several employees, but each employee can also be part of several departments.

许多员工和部门之间的关系。删除部门时,我想删除所有只属于该部门的员工,并删除属于其他部门成员的所有员工与该部门的关系。

So there is a many-to-many relationship between employees and departments. When deleting a department I would like to delete all employees that are only part of that department and nullify the relationship to this department for all employees that are also member of another department.

在两个方向上的级联规则会做到吗?

Would a cascade-rule in both directions do that? Or does a cascade rule automatically delete all employees of a department regardless of other affiliations?

推荐答案

级联规则会自动删除对象的所有员工在目的地。所以,如果您删除一个部门,员工将被删除,无论他们在哪个部门。

A cascade rule will automatically delete the objects at the destination. So, if you delete a department, the employees will be deleted regardless of the number of departments they're in.

这听起来像你想要的行为有点多细致入微,只删除孤儿员工(即没有部门的员工)。当你删除一个部门,找到这些部门的好方法是做这样的:

It sounds like the behavior you want is a little more nuanced, to delete only the "orphaned" employees -- i.e. those that don't have a department. When you delete a department, a good way of finding those would be to do something like this:

NSManagedObject *doomedDepartment = // get the department to be deleted

NSSet *employees = [doomedDepartment valueForKey:@"employees"];
NSSet *orphanedEmployees = [employees filteredSetUsingPredicate:[NSPredicate predicateWithFormat:@"departments.@count == 1"]];
for (NSManagedObject *orphanedEmployee in orphanedEmployees) {
    [managedObjectContext deleteObject:orphanedEmployee];
}    

[managedObjectContext deleteObject:doomedDepartment];

这篇关于核心数据删除规则和多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆