spatie / laravel-query-builder

Easily build Eloquent queries from API requests
https://spatie.be/docs/laravel-query-builder
MIT License
4.06k stars 397 forks source link

Nested include not working with custom include #730

Closed regnerisch closed 2 years ago

regnerisch commented 2 years ago

Hey,

first: Great Package! I use it a lot, and it's doing a great job! 

Today I ran in an issue. I have a class like: 

class LearningShowQuery extends QueryBuilder
{
    public function __construct(Request $request)
    {
        $subject = Learning::query()
            ->where('status', 'active');

        parent::__construct($subject, $request);

        $this->allowedIncludes([
            'partner',
            'categories',
            'cover',
            'steps',
            AllowedInclude::custom('steps.products', new ProductInclude()),
            'steps.products.thumbnail',
            'thumbnail'
        ]);

        $this->defaultSort('-created_at');

        $this->allowedSorts([
            'id',
            AllowedSort::field('createdAt', 'created_at')
        ]);
    }
}

We call the API with /learnings?include=steps,steps.products,steps.products.thumbnail. But adding the steps.products.thumbnail include overwrites the things I do in ProductInclude

class ProductInclude implements IncludeInterface
{
    public function __invoke(Builder $query, string $include)
    {
        $query->with($include, function ($qb) {
            $user = auth()->user();

            $qb
                ->addAverageRating()
                ->addRatedBy($user)
                ->addReadBy($user);
        });
    }
}

So our response only contains the thumbnail but avgRating, rated and read are null. Removing the steps.products.thumbnail include let return avgRating, rated and read the right values. 

I'm not sure if it's a bug, or it's related to how Laravel builds queries - but maybe you can provide a solution or at least tell me how I could make it work with a custom include and a nested relation.

Thanks in advance

spatie-bot commented 2 years ago

Dear contributor,

because this issue seems to be inactive for quite some time now, I've automatically closed it. If you feel this issue deserves some attention from my human colleagues feel free to reopen it.

lloricode commented 2 months ago

up