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

Fix whereIn subquery for Laravel 5.8+ #29

Merged
merged 4 commits into from
Oct 29, 2020
Merged

Conversation

szainmehdi
Copy link
Contributor

The way Laravel handles subqueries in the whereIn() method has changed in Laravel 5.8. (before, after). When using this library, any query bindings in the subquery within a whereIn clause were discarded, resulting in SQL errors.

For example:

// Terrible example query but hopefully, it gets the point across.
$query = Product::query()->where('type', 'physical')->whereIn('id', function ($sub) {
    $sub->select('product_id')->from('orders')->where('total', '>',  25.00);
});


dd($query->toSql(), $query->getBindings());

// Before this fix, in Laravel 5.8+
// select * from "products" where "type" = ? and "id" in (select "product_id" from "orders" where "total" > ?)
// [0 => 'physical']

// After this fix, in Laravel 5.8+
// [0 => 'physical', 1 => 25.00]

Before, when a query with a whereIn clause with a subquery was performed, the $where['type'] would be set to InSub or NotInSub depending on the operator, in which case our custom whereIn method would basically do nothing and return early.

if ($where['type'] === 'InSub' || $where['type'] === 'NotInSub') {
$this->query->wheres[] = $where;
return parent::whereIn($column, $values, $boolean, $not);
}

Sidenote: we shouldn't be calling parent::whereIn() again here since we've already called it in the lines above. This has also been corrected in this PR.

Now, with the changes in Laravel 5.8+, the check we were performing no longer applies. The $where['type'] is always either In or NotIn. Instead of checking the value of $where['type'], we can just check to see if it's "queryable" using the same logic that the Illuminate\Database\Query\Builder class uses, and return early like before.

@szainmehdi szainmehdi merged commit f91eb9d into master Oct 29, 2020
@szainmehdi szainmehdi deleted the where-in-subquery-fix branch October 29, 2020 14:39
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.

None yet

4 participants