Skip to content

Many To Many Relationships

BlairAllegrotech edited this page Apr 27, 2016 · 5 revisions

##Many To Many Relationship Configuration

JsonApi does not provide any specific notation for expressing manyToMany relationships. A JsonApi resource can have one or more oneToMany relationships but if another JsonApi resource also has a relationship to the same resource then this is still represented as a oneToMany relation in each resource. This is more like a document database would represent the relationships between documents.

A relational representation however requires an implementation specific joining table so that multiple can refer to each other. This is a relational implementation specific requirement. js-data represents data in a way that closely represents a relational system. It uses foreign keys for example for oneToMany relationships. For a manyToMany relationship this would require multiple localKey's (which is possible in js-data).

I have chosen to represent manyToMany relationships via a joining table which most people who have dealt with relational databases would be familiar with.

In order for the adapter to detect that a relationship should be represented as a manyToMany and not the default oneToMany additional meta data was added to the js-data resource configuration which describes the manyToMany relationship.

 meta: {
       // Tells adapter that this is a joining table to person used for many to many relations
        article_person : { type: 'person', joinType: 'article_to_person' }
}

This additional configuration is required at each end of the manyToMany so that behind the scenes this adapter can transparently create and populate this joining data. I consider this joining table some what of an implementation details in much the same way that a database ORM tool such as NHibernate might. With an ORM if we describe a relationship as a manyToMany the ORM will automatically create the relational database structure to represent this relationship behind the scenes which would typically include a joining table.

Here i have shown the relationships between the various pieces of js-data configuration and a JsonApi document containing a 'manyToMany' relationship.

See the examples folder for the json and js-data configuration below and the test/examples.js file for related tests.

TODO Image to be posted soon

Js-Data, JsonApi manyToMany Configuration Example

Clone this wiki locally