Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle many-to-many relations in CloudKit

I'm trying to create a tagging system using CloudKit. I have a type called Article and an tag type called Tag. Each article can have multiple tags applied. I want my data to be normalied so since same tags can appear on several articles and articles can have multiple tags, I need a many-to-many relation. In old school DB-stuff this would require a junction table.

How do you do that in CloudKit?

In any of Apples documentation I can only find examples of one-to-many relations.

So I have created a junction-table type called ArticleTag, that consists og two CKReferences. One for the Article reference and one for the Tag reference.

This should work, but what is the best way to query for tags per article?

Kind regards, Esben

like image 897
esbenr Avatar asked Jul 07 '15 19:07

esbenr


1 Answers

There isn't currently any mechanism to do "join" queries in CloudKit like a traditional relational database, however you should be able to accomplish what you want by using a field with the type "Reference List" on your Articles. Let's assume the following:

  1. Your Article record type has a "tags" field of type Reference List. You can set this up in the CloudKit Dashboard.
  2. You have a Tag record type
  3. When tagging an Article, you first lookup (and potentially create) a Tag record for each tag, then you add a CKReference to your Article.tags list field using each of the Tag record IDs.

You can then lookup an Article's tags using the IDs in the tags field, and you can find all Articles tagged with a specific tag by using the Tag record ID and a CKQuery predicate that uses the CONTAINS operation to check for list membership.

like image 196
Dave Browning Avatar answered Oct 22 '22 14:10

Dave Browning