Reputation: 3081
So in my app I have an Entity called Cards and another called Transactions.
The Transaction entity have the attributes: Date, Location and Amount. So if a user spends his money in 10 locations, I need to have 10 entries in the Transactions for a single card.
I just started working with Core Data and it's getting messy.
I also use MagicalRecord to work with Core Data.
I was able to CRUD the cards entity, adding, updating etc... is all good.
The thing is, I need to add the transactions to a card and don't know how to start with this relationship. How to add transactions to the card and then fetch the card with all the transactions?
Any insight would be much appreciated.
Upvotes: 0
Views: 202
Reputation: 14068
If I understood you right, then you establish a relation between them.
Card -> Transaction is a To-Many relation. See the right hand pane in xcode for this option. Add an inverse. Always add an inverse. So you have a not To-Many relation Transaction -> Card Right? There is only one card for each transaction?
The rest of the answer depends on how you access the data. I suggest to create a model class for each entity. You know how? Click on the entity then go to file/new/file, select core data then NSManagedObjectSubclass and it will be created for you. This class has methods for adding related items.
myTransaction.card = myCard;
respectively
[myCard addTransactionsObject:myTransaction];
Assuming of course that myCard and myTransaction are the classes and that your to-one relation is named card and the to-many relation is named transactions.
Upvotes: 1
Reputation: 5966
Just set a one-to-many relationship from Card
to Transaction
Entity, and then simply get all of your (previously added by [card addTransactionsObject:newTransaction]
call) transactions using that relation: card.transactions
.
Don't forget to add an inverse relation fromTransaction
to Card
!
Upvotes: 0