4
votes

I have an entity Library that mains two lists of Books. It is important that the library maintain these two lists of books. On my Library entity I have a relationship thats one to many from each list to my Book entity. Likewise, Book has a relationship "library". I'm having some problems with my data being erased from the database and I read that I should be setting up inverse relationships to help with data integrity. In this case however, a Book would want to be able to set up an inverse relationship with each list on my Library entity. How can I accomplish this?

My naive first thought is to implement relationships for both lists. So a book has a relationship "libraryForList1" and "libraryForList2" so that it can have an inverse for each relationship. I'll never have to actually reference these properties because according to the Core Data spec, if I add a book to one of the library lists, it automatically takes care of setting the library as that books owner.

1
See stackoverflow.com/questions/4985075/… , among others. If your library can own books in two different ways, then a book can belong to a library in two different ways, and both need to be modeled separately.rgeorge

1 Answers

5
votes

Your "naive first thought" is essentially correct: If your Library entity has two one-to-many relationships with Books (for clarity let's call the relationships ownedBooks and borrowedBooks), then your Book entity should have to-one inverse relationships (owningLibrary and borrowingLibrary) and then Core Data will make your life easier.

You may also need to think about the delete rules on these relationships: If a Book is deleted for some reason, the delete rules for the owningLibrary and borrowingLibrary would likely be Nullify – that is, both libraries would remove the Book from their lists. Deleting a Library that still has Books seems like a bad idea, so maybe the delete rule for ownedBooks and borrowedBooks should be Deny: A Library can't be deleted until the books are all accounted for (and removed from the Library).