开发者

Many to Many relationship for single entity

开发者 https://www.devze.com 2023-02-16 14:40 出处:网络
I\'m currently writing my first project using core data, and am having trouble working out how to query the relationship between some of my data.

I'm currently writing my first project using core data, and am having trouble working out how to query the relationship between some of my data.

In sql language, i have a Country table, which joins to a CountryLink M-M table containing the following fields:

  • countryId1
  • countryId2
  • bearing

What would be the correct way to model this in Core Data?

So far i have set up a single Country entity and a CountryLink entity (containing only a bearing field) and have added two 1-to-Many relationships from Country to Cou开发者_StackOverflow中文版ntryLink ('CountryLink1' and 'CountryLink2').

I've run the project and looked at the Sqlite db structure produced by Core Data (found here, using this sqlite gui), and the M-M join table seems correct (it contains the bearing, CountryLink1 and CountryLink2 fields), but i'm not sure how i would go about carrying out a fetch request for a single Country NSManagedObject to return an array of related Countries and their bearings?

Any help or related links would be much appreciated.

Thanks, Ted


First a word of warning:

Core Data is not SQL. Entities are not tables. Objects are not rows. Columns are not attributes. Core Data is an object graph management system that may or may not persist the object graph and may or may not use SQL far behind the scenes to do so. Trying to think of Core Data in SQL terms will cause you to completely misunderstand Core Data and result in much grief and wasted time.

See the Tequilla advice

Now, forgetting SQL and thinking in object graphs, your entities would look something like this:

Country{
    someAttribute:string // or whatever
    countryLinks<-->>CountryLink.country
}

CountryLink{
    countryID1:string // or whatever
    countryID2:string // or whatever
    country<<-->Country.countryLinks
}

As you add Country and CountryLink objects you add them to the relationships as needed. Then to find CountryLink objects related to a specific Country object, you would perform a fetch on the Country entity for Country objects matching some criteria. Once you have that object, you simply ask it for the CountryLink objects in its countryLinks relationship. And your done.

The important thing to remember here is that entities in combination with managedObjects are intended to model real-world objects, conditions or events and the relationship between the same. e.g. a person and his cars. SQL doesn't really model or simulate, it just stores.

0

精彩评论

暂无评论...
验证码 换一张
取 消