laravel-responder icon indicating copy to clipboard operation
laravel-responder copied to clipboard

Including Relationships

Open Hesesses opened this issue 6 years ago • 2 comments

Hello,

I have Transformers:

class ModelTransformer extends Transformer
{
    protected $load = [
        "organisation" => OrganisationTransformer::class
    ];

and

class OrganisationTransformer extends Transformer
{
    protected $relations = [
        'contact',
        'AnotherRelation' => AnotherRelationTransformer::class,
    ];

    protected $load = [];

    public function transform(Organisation $organisation)
    {
        return [
            'id'    => (int) $organisation->id,
            'name'  => (string) $organisation->name,
        ];
    }

    public function includeContact(Organisation $organisation)
    {
        return Transformation::make($organisation, OrganisationContactTransformer::class)->with('mailingAddress')->transform();
    }
}

Get request to /organisation?with=contact works Get request to /model?with=organisation works Get request to /model?with=organisation.AnotherRelation works Get request to /model?with=organisation.contact doesnt work

Any ideas why with=organisation.contact relation is not working

Hesesses avatar Oct 24 '19 18:10 Hesesses

Hey, not sure, but I believe it has something to do with how the relations are resolved recursively. I'll see if I can replicate your scenario.

However, I'm not sure I understand why you're using an includeContact method to manually perform the transformation. Wouldn't

protected $relations = [
        'contact' => OrganisationContactTransformer::class,
        'AnotherRelation' => AnotherRelationTransformer::class,
];

And add 'mailingAddress' to OrganisationContactTransformer's $load property do the same?

flugg avatar Oct 25 '19 08:10 flugg

Its because contact is not a real relation, Organisation has contact fields, but those are normally not needed. so those would only be returned when needed (with=contact)

The errors message is:

{
"status":422,
"success":false,
"error":{
    "code":"relation_not_found",
    "message":null
  }
}

Illuminate\Database\Eloquent\RelationNotFoundException: Call to undefined relationship [contact] on model [App\Organisation].

Hesesses avatar Oct 25 '19 09:10 Hesesses