spatie / laravel-query-builder

Easily build Eloquent queries from API requests

Home Page:https://spatie.be/docs/laravel-query-builder

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Nested include not working with custom include

regnerisch opened this issue · comments

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

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.