Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[6.x] Fix Builder::withCount() binding error when a scope is added into related model with binding in a sub-select #30869

Merged
merged 2 commits into from
Dec 18, 2019

Conversation

miklcct
Copy link
Contributor

@miklcct miklcct commented Dec 18, 2019

In current Laravel, Builder::withCount() causes an error if the related model has a scope which adds a sub-select with bindings, for example, the following scope attempts to add a column called "liked" into Likeable models, but causes an error when a model with it is loaded in Builder::withCount().

class LikeScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        if ($model instanceof Likeable) {
            if ($builder->getQuery()->columns === null) {
                $builder->select(['*']);
            }
            $builder->selectSub(
                Like::whereColumn('likeable_id', '=', $model->getTable() . '.id')->whereLikeableType($model->getMorphClass())->whereUserId(
                    app(User::class)->id
                )
                    ->selectRaw('count(*)')
                ,
                'liked'
            );
        }
    }
}

It's because Builder::withCount() removes extra columns added by the scope when loading the count, but forgets to remove the extra "select" bindings added.

This one-line patch fixes the problem.

@GrahamCampbell GrahamCampbell changed the title Fix Builder::withCount() binding error when a scope is added into related model with binding in a sub-select. [6.x] Fix Builder::withCount() binding error when a scope is added into related model with binding in a sub-select Dec 18, 2019
@taylorotwell taylorotwell merged commit 6b8ae3d into laravel:6.x Dec 18, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants