Created
March 1, 2016 12:52
-
-
Save franzliedke/e351e4a4d4f7d3d481a4 to your computer and use it in GitHub Desktop.
Laravel scope with binding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class SomeModel extends Eloquent | |
{ | |
public function scopeSomething(Builder $query, $something) | |
{ | |
// This will properly set up a binding | |
return $query->where('something', $something); | |
} | |
public function scopeSomethingAndOr(Builder $query, $something, $connector) | |
{ | |
if ($connector == 'and') { | |
return $query->where('something', $something); | |
} else { | |
return $query->orWhere('something', $something); | |
} | |
// Really, you can shorten this to the following: | |
// return $query->where('something', '=', $something, $connector) | |
} | |
} |
Additionally, if I mix a scope like the one above with another one as simple as return $query->where('search_type', 'proximity');
, the mixed named and positional parameters
error returns.
Hmm, whereRaw
accepts a second parameter called bindings: https://github.com/laravel/framework/blob/c858d541b1a05c3a13734c17f5d9e69fe6e1502b/src/Illuminate/Database/Query/Builder.php#L564
You should try that (with numeric indices and question marks as placeholders, yes).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think my issue is that I need to use
WHERE st_contains(bounds, POINT(:lat, :lng)
What I have is
However, when I combine it with another scope that uses
SELECT st_distance(location, POINT(:latDistance, :lngDistance)) as distance
I get an error for incorrect number of parameters. I assume this is because the scope wipes out the previous bindings.If I use
$query->getBindings()
with an array merge, it returns a numerically indexed array, without the keys I previously set. This then makes PDO complain about mixed named and numeric parameters.If I change all my queries to use
?
instead of named parameters, Laravel sets them in the wrong order :/.