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

Moprh + include = method not found #558

Closed rekrios closed 3 years ago

rekrios commented 4 years ago

Hi. Is there any easy way to include resources after polymorp(MorphTo) relationship ? Problem: after polymorph relationship different resources have different relationships and you will get fatal with 'method/relationship not found'. I can make eager loading for such resources via

  $morphTo->morphWith([
    Model1::class => [
      'relation1.relation11'
    ],
    Model2::class => [
      'relation2',
    ],
  ]);

But can't say the same for includes. Maybe there is the way to show them even without them in $_GET path ?

rekrios commented 4 years ago

Found way #1: Without $_GET's included path, you can set includes through schema's

    public function getIncludePaths()
    {
        return ['relation1.relation11', 'relation2.relation22'];
    }

But not convenient for all cases. Maybe someone know's better way

lindyhopchris commented 4 years ago

Yeah, polymorphic relationships present a number of problems that I don't think I've ever fully cracked. Think they need some work in future versions of this package to get them working better. Sorry not to be able to provide an immediate fix.

bbprojectnet commented 3 years ago

I have similar case in my project. I solved this by defining dummy relations in model to omit error:

trait HasNoneRelations
{
    public function __call($method, $parameters)
    {
        if (in_array($method, $this->getNoneRelations())) {
            return $this->belongsToNone();
        }

        return parent::__call($method, $parameters);
    }

    public function getNoneRelations(): array
    {
        return $this->noneRelations ?? [];
    }

    protected function belongsToNone(): BelongsTo
    {
        return new BelongsTo($this->newQuery(), $this, '', '', '');
    }
}

and then, in model:

class Game extends Model
{
    use HasNoneRelations;

    protected $noneRelations = [
        'attachment',
        'attachments',
        'reads',
        'other-non-existing-relation',
    ];
}

now you can include through morph relationship :)

I am curious about a more elegant solution.

lindyhopchris commented 3 years ago

Closing this in favour of polymorphic relations in the new package - laravel-json-api/laravel