laravel-responder
laravel-responder copied to clipboard
unnecessary db called when using `with()` method
I can't find it is intended behavior, but it seems worth to reporting.
// in my controller
public function index()
{
// find Users with user's photo.
// SELECT * FROM users
// SELECT * FROM photos WHERE user_id IN (?, ?....?)
$users = User::with('photos');
// this will execute another db call.
// SELECT * FROM photos WHERE user_id IN (?, ?....?)
return responder()->success($users)->with('photos');
}
// UserTransformer
public class UserTransformer extends Transformer
{
protected $relations = [
'photos' => PhotoTransformer::class,
];
public function transform(User $user)
{
return [
'id' => $user->id,
'name' => $user->name,
//.. and so on
];
}
// if includeXxxx method exists, eager loaded relation will use it
// else just call other db call SELECT * FROM photos WHERE user_id IN (?, ?....?)
public function includePhotos(User $user)
{
return $user->photos;
}
}
Hey! Sorry for the late reply. The package will automatically eager load all relationships provided with the with method. I guess we could add a check if the relations have already been loaded and not run a new query then. What do you think?
would be great 👍
Up for this feature. When I have an temporary eloquent (through new model()), it can't resolve the relationship. Because the model doesn't have any id yet.
can we use $data->loadMissing instead of $data->load at TransformBuilder@eagerLoadRelations ?
Hey @cberio, definitely not a bad idea, however, loadMissing was added with Laravel 5.6 if I remember correctly. I don't want to bring in a breaking change for people on earlier versions, but I suppose we can do a check if loadMissing exists, and if not fallback to just using load?