Вопрос

lets say i have an entity A and a entity B. The relationship is 1:1. If i delete A then B should also be deleted. I have set this up with a cascade delete rule. Now lets assume i add another entity C which has a relationship 1:1 to B.

I'm not sure how to handle this appropriately. If A and C have the same B should it be the same instance of B? Or should i duplicate the entry ? If it is the same then deleting A can not delete B anymore if C has a reference to it.

Furthermore how can i enforce this 1:1 relationship between A and B ? At the moment when i create the A entity i also create a B entity not checking if it is already in the data base. This does not fail, and causes duplicates of B.

Edit: For a better understanding what i'm trying to achieve:

A must always have a B. C must also always have a B.

For example lets assume i have an entity Shop (B) and an entity Favorite(A). In the Future i might add another entity which will also use Shop. So if the user creates a Favorite he will give it a name and a Shop. Now if i don't check if this Shop is already in the DB i would create another one. On the other hand if i allow duplicates i can use cascade delete rule and must not be scared that if i delete a Favorite it would leave another Favorite with an empty Shop.

I feel a little lost and i'm not sure whats the best practise in such scenarios. Any help is appreceated.

Это было полезно?

Решение

It depends on what you are trying to do. If a B cannot exist without an A, then the cascade would still apply. However, if C can cause B to still exist, then you should remove the cascade delete.

But this also begs the question as to if any one of them doesn't exist, will the others then not exist. Which may mean that you need to delete both B and C if A gets deleted.

Lets apply this to an example.

A = Body B = Head C = Brain

Lets say these are all the things a human needs to be alive. Without a body, the head and brain won't work. This is similarly true for the rest of the parts. So if any of these parts die, the others die.

Ok, now if A and C have the same B, then that should be a unique B, not a duplicate.

Any implementation of CoreData should check for the existence of a entity before creating a new one unless you can guarantee it will only belong to one specific entity. Your A and B must always be unique if you are going to not check for duplicates. There are very few always unique real world values. A specific time would an example of an always unique instance. This second only ever exists right now, and will never exist again, nor has it existed before.

If a new A creates a B, then that is fine. However, if both A and C can have the same B, then you must check for an existing B, otherwise A and C will never be able to share a B. If your A's only have 1 B forever, and nothing else uses B, then you can do this as long as you always create unique A's.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top