dingo / api

A RESTful API package for the Laravel and Lumen frameworks.
BSD 3-Clause "New" or "Revised" License
9.32k stars 1.25k forks source link

Eager loading eloquent model relationships falls back to lazy loading. #1259

Open NikiSchlifke opened 7 years ago

NikiSchlifke commented 7 years ago

I have an Eloquent model that has several relationships to other models, some of which have nested relationships themselves. Eager loading theses relationships from within Eloquent at getting a collection containing the loaded data seems pretty straight forward. However when I use this collection with Dingo's response()->collection($collection, $transformer) the eager loaded data is ignored and it falls back to lazy load everything.

$collection = Model::query()->with('relation', 'relation.nested')->get();
$response = $this->response()->collection($collection, $transformer);

The transform method is like:

public function transform(Model $model) { return ['nested' => $model->relation()->first()->nested]; }

Should that in principle already use eager loading or do I have to use Fractals $defaultIncludes = ['relation']; and includeRelation() mechanism like here? http://fractal.thephpleague.com/transformers/

catalinux commented 7 years ago

There are two ways of doing out of box

  1. Add them in defaultIncludes and define the methods that map these includes on the Transformer
  2. Add the methods on the Transformer and use ?include=comments parameter to your end points.

I am not aware of any way of doing this from your controller.