问题
I have 2 entities: Train
and Station
Each train stops at multiple stations, i.e. Train <--->> Station
.
The list of stations a train stops at is different from the list of stations some other train stops at.
How do I correctly save and fetch the list of stations for a particular train?
Thanks
回答1:
Does this:
Train <--->> Station
mean you have a one to many relationship? If so, it doesn't work, unless only one train can stop at each station. What I would do is create a third entity, call it say "stop" with two relations, a many to one to Train
and a many to one to Station
. It wil look something like
+-----+ +-------+
|Train| |Stop | +-------+
+-----+ +-------+ |Station|
|stops|<---->>|train | +-------+
+-----+ |station|<<----->|stops |
+-------+ +-------+
To find all the stations a particular train stops at, just look at the stops
property of the Train
which will be an NSSet
of Stop
objects each of which has a property which is a station the train stops at.
To add new stops, just create a new Stop
object and set its train
and station
properties appropriately.
来源:https://stackoverflow.com/questions/8310652/core-data-one-to-many-relationships-fetching-specific-related-entities