Search code examples
xcodecore-dataswift3datamodel

Core Data Relationship settings


Im creating an app which got the entities "Plan" and "Tool". A "Tool" must be unique and tools get linked to different plans. For example Plan "A" got the tools "a", "b", and "c". And another Plan "B" got the tools "b", "c" and "d". So "b" and "c" are both in "A" and "B". So a Tool can be linked to more plans.

How can I do this with the core data relationships? I tried some different settings and observed the database with "DB Browser for SQLite" but its not working as Id like to.

Example:

enter image description here

Which settings must my relationships have?


Solution

  • From Apple's documentation:

    Many-to-Many Relationships

    You define a many-to-many relationship using two to-many relationships. The first to-many relationship goes from the first entity (the source entity) to the second entity (the destination). The second to-many relationship goes from the second entity (the original destination entity) to the first entity (the original source entity). You then set each to be the inverse of the other.

    In your case it should look like this:

    Model Diagram

    Here you see the relationship properties:

    Relationship Properties 1

    Relationship Properties 2

    Again, from Apple's documentation:

    IMPORTANT

    You must define many-to-many relationships in both directions—that is, you must specify two relationships, each being the inverse of the other. You can’t just define a to-many relationship in one direction and try to use it as a many-to-many. If you do, you will end up with referential integrity problems.