user4951
user4951

Reputation: 33090

How does cascade delete works in many to many relationship in coredata works?

Say, we have 2 entities : Parents and children.

When a parent is deleted, then all the children are erased too.

Great.

Now we have entities called lover.

Each individuals can "love" many other individuals and be loved by many.

What happen if an individual deleted?

Does cascade delete:

  1. Don't work at all?
  2. Delete you when the last person that love you is deleted?

Or what?

Upvotes: 2

Views: 1093

Answers (1)

Nikita Pestrov
Nikita Pestrov

Reputation: 5966

I think, that you shouldn't use cascade with to-many this way, because, as it deletes all the lovers of the object you delete, it may go further and further and delete the whole database.

So the better approach for you is to have a intermediate (“join”) entity, for example, loverInfo. Here's, how the Apple suggest you to do that, based on the friends relationship.

A common example of a relationship that is initially modeled as a many-to-many relationship that’s the inverse of itself is “friends”. Although it’s the case that you are your cousin’s cousin whether they like it or not, it’s not necessarily the case that you are your friend’s friend. For this sort of relationship, you should use an intermediate (“join”) entity. An advantage of the intermediate entity is that you can also use it to add more information to the relationship—for example a “FriendInfo” entity might include some indication of the strength of the friendship with a “ranking” attribute. This is illustrated here

FIgure 3

In this example, Person has two to-many relationships to FriendInfo: friends represents the source person’s friends, and befriendedBy represents those who count the source as their friend. FriendInfo represents information about one friendship, “in one direction.” A given instance notes who the source is, and one person they consider to be their friend. If the feeling is mutual, then there will be a corresponding instance where source and friend are swapped. There are several other considerations when dealing with this sort of model:

  • To establish a friendship from one person to another, you have to create an instance of FriendInfo. If both people like each other, you have to create two instances of FriendInfo

  • To break a friendship, you must delete the appropriate instance of FriendInfo.

  • The delete rule from Person to FriendInfo should be cascade. If a person is removed from the store, then the FriendInfo instance becomes invalid, so must also be removed.
  • As a corollary, the relationships from FriendInfo to Person must not be optional—an instance of FriendInfo is invalid if the source or friend is null.

Upvotes: 1

Related Questions