Search code examples
objective-ccocoa-touchiosentities

iOS iPhone Getting 1 to Many Entity


Basically I have an entity that contains food dishes and another that contains wine. Each dish has wine recommendations. I need to be able to select a dish and see the wine recommendations that come with that dish. Different dishes can have the same wine recommended for it.

Normally in SQL I would create a link table to achieve this but I am a bit stumped here, can anyone help?


Solution

  • Core Data handles the details of "to-many" relationships under the hood for you, you don't need to make intermediary tables.

    Open your Core Data .xcdatamodel file, select the Food Entity, and click Add Relationship. Name the relationship wines. Make its destination entity the Wine entity. Open the Data Model Inspector (option-cmd-3) and select To-Many Relationship.

    Now select the Wine entity. Create a relationship called foods. In the Data Model Inspector make the relationship's Desination the Food entity, it's inverse relationship is wines and set it to be a To-Many Relationship as well.

    Now each instance of Food can have many Wines and each instance of Wine can have many Foods.