tobyzerner / json-api-php

JSON-API (http://jsonapi.org) responses in PHP.
MIT License
436 stars 79 forks source link

Metadata for many-to-many relations #48

Closed quetzyg closed 9 years ago

quetzyg commented 9 years ago

Hi there!

When dealing with many-to-many relations, sometimes there's the need to include data which doesn't belong to any of the types, but does belong to the relation they form (the pivot table).

Currently, there's no way to add that kind of data, since the only thing that goes into relationships is the id and the type of any related type, as we can see here.

I asked how we could handle that case in the JSON API discuss, in which I was pointed to this other question, from where I got my answer.

What's the possibility to add that feature to the library?

Cheers, Quetzy

tobyzerner commented 9 years ago

Thanks for reporting. I've just committed a fix in the 0.2 branch; meta information will be added to resource identifier objects if present. When composing your relationship data, you can either create the Resources beforehand and set the metadata:

public function tags()
{
    return new ClosureHasManyBuilder($serializer = new TagSerializer, function ($post) use ($serializer) {
        return array_map(function ($tag) use ($serializer) {
            $resource = new Resource($tag, $serializer);
            $resource->setMeta($tag->metadata);
            return $resource;
        }, $post->tags);
    });
}

... or you can return the raw data and configure the resources afterwards:

public function tags()
{
    $builder = new ClosureHasManyBuilder(new TagSerializer, function ($post) {
        return $post->tags;
    });

    $builder->configure(function (Relationship $relationship) {
        foreach ($relationship->getData()->getResources() as $resource) {
            $resource->setMeta($resource->getData()->metadata);
        }
    });

    return $builder;
}

(Note: haven't actually tested this!)

quetzyg commented 9 years ago

Brilliant! :+1: