cloudcreativity / laravel-json-api

JSON API (jsonapi.org) package for Laravel applications.
http://laravel-json-api.readthedocs.io/en/latest/
Apache License 2.0
780 stars 109 forks source link

Creating Record With Related Morph One #503

Closed yoelpc4 closed 4 years ago

yoelpc4 commented 4 years ago

I have Project model morph one to Document model

app/Models/Project.php

    /**
     * Project morph one contract document
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphOne
     */
    public function contractDocument()
    {
        return $this->morphOne(Document::class, 'documentable');
    }

app/Models/Document.php

    /**
     * Document morph to documentable
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphTo
     */
    public function documentable()
    {
        return $this->morphTo();
    }

with relation registration in adapter

app/JsonApi/v1/Projects/Adapter.php

    /**
     * Project morph one contract document
     *
     * @return \CloudCreativity\LaravelJsonApi\Eloquent\HasOne
     */
    protected function contractDocument()
    {
        return $this->hasOne();
    }

When creating project via [POST] https://api.test/v1/projects with payload

{
    "data": {
        "type": "projects",
        "attributes": {
            "name": "1st project",
        },
        "relationships": {
            "contractDocument": {
                "data": {
                    "type": "documents",
                    "id": "90"
                }
            }
        }
    }
}

I got an internal server error (500) when creating record with message

JSON API relation HasOne cannot be used for an Eloquent MorphOne relation

https://github.com/cloudcreativity/laravel-json-api/blob/71fc1a8d5f8613c6972c339c2ee23d494acf66df/src/Eloquent/Concerns/QueriesRelations.php#L35-L55

Do you have any idea?

lindyhopchris commented 4 years ago

Thanks for this. Morph one probably isn't supported just because it has been introduced since I wrote the code. I need to add tests for this scenario to check that it works, and bug fix it if it doesn't.

lindyhopchris commented 4 years ago

This is definitely a missing feature. I've added it and it will be tagged as 1.7.0 and 2.0.0-beta.3.