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 rel开发者_高级运维ationship "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.
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).
精彩评论