James Y
James Y

Reputation: 113

Core Data many to many through table with custom fields

My object model has article and media where articles reference media in a many to many relationship. The media may have different ordering and need to store the order of that media relative to the article, i,e, not on the media itself.

Core Data internally generates a sqlite database with the through table as:

article_id, media_id

Core Data/MagicalRecord objects are article and media:

class Article: NSManagedObject {
  ...
  @NSManaged var media: NSSet
}

class Media: NSManagedObject {
  ...
}

Is there a means in Core Data to persist the order of media in a through table mechanism? Instead I seem to need to create a new media record with its own position each time that media is used by an article.

In Django and Rails I make use of a through table in my model to store a position/order integer that says this media for this article is in this order. The table would have these columns:

article_id, media_id, position

It seems a through table with custom fields is not possible in Core Data?

Upvotes: 2

Views: 287

Answers (1)

pbasdf
pbasdf

Reputation: 21536

I would remove the many-many relationship and instead create a third entity, say a Reference, which fulfils the same purpose as your "through table". Establish one-many relationships from Article to Reference, and from Media to Reference, and add a position attribute:

enter image description here

This almost exactly mirrors your Django/Rails solution, though it does require you to maintain the position attribute for the References - if you remove a reference from an article, you need to update the position attribute for any remaining references in the article.

Alternatively,...

Another solution would be to keep the many-many relationship, but to specify in the data model that the relationship from Article to Media is ordered:

enter image description here

If you inspect the underlying SQLite file, you will find that it has created an intermediate table with an additional attribute to store the order. You cannot access this value directly, CoreData updates it as you insert and remove objects to/from the Article's media relationship.

Upvotes: 3

Related Questions