Pivot data for many-to-many relations


#1

Hi everyone!

I couldn’t find any documentation concerning pivot data from many-to-many relations, when returning JSON API responses.
To illustrate my point, consider a relation between Books and Librarians, where many books can be sold by many librarians, and many librarians can sell many books.

The following, would be the simple result for a Book with id 2, which is being sold by Librarian 1 and 2.
The pivot data in this case is the price, since the same Book can be sold for a different price, depending on the Librarian:

{
    "data": [
        {
            "type": "books",
            "id": "2",
            "attributes": {
                "title": "My Book",
                "isbn": "972-662-905-4"
            },
            "relationships": {
                "librarians": {
                    "data": [
                        {
                            "type": "librarians",
                            "id": "1",
                            "price": "10"
                        },
                        {
                            "type": "librarians",
                            "id": "2",
                            "price": "12"
                        }
                    ]
                }
            }
        }
    ]
}

As you can see in the example above, the only place where it makes sense to put the price is in the relationships.
All the examples I found don’t seem to be for many-to-many relations, or they purely don’t have any relevant pivot data to include, so I wanted to know if this is a correct way of returning the relation data, or if this is considered an extension to the spec, given that all examples I come accross with, only have type and id, like so:

"data": { "type": "librarians", "id": "1" }

Also, all the PHP JSON API library implementations I’ve tested don’t accommodate for this, so I wonder.

I appreciate any time you take reading this.

Best,
Quetzy


Representing many-to-many pivot data
How to handle a composite ID in a many-to-many?
#2

Check out Metadata About Relationships and lmk if you still have any questions.

Cheers,
Ethan


#3

Hello Ethan,

Thanks for the tip!
I guess using the meta property might be the best option I have.

Regards,
Quetzy


#4

@quetzyg did you end up solving your issue? I’m running into something similar.