Skip to content

How to filter by morph relation? #309

Open
@MyLittleVerdant

Description

@MyLittleVerdant

For an illustrative example. I have model AgreementPartner with fields entity_type, entity_id. I described morph relation with other models like this

In Models/AgreementPartner:

 public function partnerable(): MorphTo
    {
        return $this->morphTo(__FUNCTION__, 'entity_type', 'entity_id');
    }

In AgreementPartnerSchema i have:

 public function fields(): iterable
    {
        return [
            ID::make()->uuid(),
        
            Str::make('entityType'),
            Str::make('entityId'),

            MorphTo::make('partnerable')->types(CarrierSchema::type(), MerchantSchema::type()),
        ];
    }

  public function filters(): iterable
    {
        return [
            WhereIdIn::make($this)->delimiter(','),

            WhereHas::make($this, 'partnerable'),
        ];
    }

And in AgreementPartnerResource:

class AgreementPartnerResource extends JsonApiResource
{
    public function relationships($request): iterable
    {
        return [
            $this->relation('agreements'),
            $this->relation('partnerable'),
        ];
    }
}

It's works fine for
/agreement-partners?include=partnerable
but i can't do this
/agreement-partners?filter[partnerable][id]=01958f45-74ff-72af-9d72-6b081b485f9a

Although if I change the description of the relation in fields() to this

BelongsTo::make('partnerable')->type(CarrierSchema::type()),

Everything will work and even add filters filter[partnerable][] for all related resources, despite the fact that now only CarrierSchema is described.

But it's seems like bug for me. Is there any other option for filtering by morph relation?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions