2
votes

In my application there are N number of Users. Each user can have N number of Categories. Each category can have N number of Books.

I have created following Entities BookMetadata, Users, Categories

BookMetadata entity is a unique collection of books data from different users.

How do I go about creating relationship between these entities.

Relationship between - Users & Categories.(one to many) or users & books (one to many, one user can have one or more than one book).

Relationship between - Categories & Books.(one to many).

enter image description here

Is my understanding about implementing these relationships correct, I'm relatively new in creating relationships in CoreData. If no or a better solution, please let me know how to go about it.

EDIT:

Consider this scenario,

User 1 -> Category 1 -> Book1,Book2.
       -> Category 2 -> Book3, Book4.

User 2 -> Category 1 -> Book1,Book2,Book3.
       -> Category 3 -> Book4

Here In the above scenario. The same Book (Book 3) has different category for the different user. How to handle this scenario?

EDIT 2:

I'm attaching a sample sqlite DB file @dropbox https://www.dropbox.com/s/nlmdojkk64bkf1b/test.sqlite.

1
Yes it is very correct. Didn't you set inverse relationship from category to user and also book to category? - Anupdas
The relationship between users and categories is wrong and must be many to many: you want an user to be able to read/buy books belonging to different categories, and, conversely, you want a book category to belong to more than one user. The relationship between categories and books is, instead, correct (one to many). - Massimo Cafaro
@Anupdas Thanks for your response. Please check my EDIT. Also what is the need for me to set a inverse relationship between category to user and also book to category, could you please explain. - Pranav Jaiswal
Can you explain the role of category in this system. Is this category user created. Is category unique to a user? With your given info category and book will also have a many-many relationship. - Anupdas
With the given info, I have updated my answer. See if it matches your requirement. - Anupdas

1 Answers

1
votes

As a convention Entities should be named as singular. The relationships should be named plural or singular relative to their relationship.

From the given information it is assumed that category is created by a user to group the books like a playlist or something. A category will be unique to user and it is not shared among users. A book can be included in any number of categories.

So this will become

User < -- >> Categories

Category <-- >> Books

Book < -- >> Categories

A relation should have two sides. Inverse let you define that. If a user can have any number of categories and a category can only have one user. Inverse of categories is a user.

enter image description here