eloquence icon indicating copy to clipboard operation
eloquence copied to clipboard

Eloquence treats parameter grouping query as subquery

Open carlfredrikhero opened this issue 4 years ago • 3 comments

Laravel support parameter grouping via a where method that takes exaktly 1 argument (a closure) : https://laravel.com/docs/7.x/queries#parameter-grouping

$users = DB::table('users')
           ->where('name', '=', 'John')
           ->where(function ($query) {
               $query->where('votes', '>', 100)
                     ->orWhere('title', '=', 'Admin');
           })
           ->get();

produces

select * from users where name = 'John' and (votes > 100 or title = 'Admin')

Subqueries are also supported with almost the same syntax. The only difference is that the where method takes a closure as the first argument and a value as a second argument.

$users = User::where(function ($query) {
    $query->select('type')
        ->from('membership')
        ->whereColumn('user_id', 'users.id')
        ->orderByDesc('start_date')
        ->limit(1);
}, 'Pro')->get();

Notice the "'Pro'" value on the last line.

Eloquence seems to interpret where(closure) as where(closure,null).

Im my case Eloquence changes the correct query:

select * from users where (name LIKE ?)

to the syntactically incorrect query

select * from users where (select * where name LIKE ?) is null

The php code to generate the query is:

$sql = static
            ::where(
                function ($query) use ($q) {
                    $query
                        ->where('name', 'LIKE', '%'.$q.'%');
                }
            )
            ->toSql();

I will try to troubleshoot this further.

carlfredrikhero avatar Oct 09 '20 07:10 carlfredrikhero

Check out https://github.com/jarektkaczyk/hookable/pull/27, still waiting for it to be merged but it worked for me.

EK1771 avatar Dec 07 '20 03:12 EK1771

@jarektkaczyk :)

PeraMika avatar Dec 08 '20 23:12 PeraMika

Oh, I'm facing the same problem.

gfernandez-me avatar Jul 25 '21 17:07 gfernandez-me