Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a recursive one-to-many relationship using core data?

I have used core data before, but this database I have to construct has a particularity that will require a special relationship that is melting my brain.

I have 2 entities, lets call them Cage and Animal.

  • Cage has one attribute name
  • Animal has a name and image attributes and must keep track of its children.

A possible structure can be something like

cage ---------- animal 1
         |
         |_____ animal 2
         |
         |_____ animal 3 ____ animal 4
                          |
                          |__ animal 5
                                  |
                                  |_____ animal 6

Looking at this structure you see that Animal 1, Animal 2 and Animal 3 have Cage as parent or are "children" objects of Cage if you will. On the other hand Animal 3 has 2 children objects (4 and 5) and Animal 5 has one children object.

I need Cage and Animal to be different entities.

So, you see that Animal objects can have other Animals as children. An animal can have one parent but multiple children. A Cage object can only have children.

I have tried to add a children relationship with destination equal to Animal and inverse equal to children (toMany) but this is what is melting my brain, because if I do this, this will be parent at one time and children at others, not to mention that the name children will make coding difficult to wrap the head around...

How do I have to build the relationships between the entities to make this work?

like image 726
Duck Avatar asked Mar 17 '23 01:03

Duck


2 Answers

First create your entities and attributes. Then create your relationships. The relationships for "animals" and "children" shout be set to "to many". Leave "cage" and "parent" set to "to one" relationship. Finally, set the destination and inverse for each relation.

Relations "animals" and "cage" should be inverse. Relations "parent" and "children" should be set to inverse.

Should look like this when you're done:

enter image description here

like image 68
picciano Avatar answered Apr 06 '23 11:04

picciano


Animals live on cage and two animals can have relationships.

I came up with following ERD

like image 22
Pramod Avatar answered Apr 06 '23 11:04

Pramod