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

unnecessary db called when using `with()` method

Open cberio opened this issue 7 years ago • 5 comments

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;
    }
}

cberio avatar Mar 27 '18 04:03 cberio

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?

flugg avatar Mar 31 '18 11:03 flugg

would be great 👍

cberio avatar Apr 02 '18 02:04 cberio

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.

lokingwei avatar Oct 22 '18 16:10 lokingwei

can we use $data->loadMissing instead of $data->load at TransformBuilder@eagerLoadRelations ?

cberio avatar Jan 08 '19 08:01 cberio

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?

flugg avatar Jan 10 '19 17:01 flugg