6

hy I'm new in laravel 4 and I have found code like this

$sub = Abc::where(..)->groupBy(..); // Eloquent Builder instance

$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )
->mergeBindings($sub->getQuery()) 
->count();

my quetion is
1. what the meaning mergeBindings($sub->getQuery()) and give me example for using mergeBindings

b4dQuetions
  • 1,549
  • 6
  • 18
  • 28

1 Answers1

15

assume your first query is like this:

$sub = Abc::where('type', 1)->groupBy(..);

then when we convert it to sql:

$sub->toSql();

this will return query string some thing like this:

SELECT * FROM abc where abc.type = ? GROUp BY ...

you can see the "?" as the type value which will be binded (replaced by 1) when the PDO executes that query string

So when we use that sub query in another query as you do in

$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )
    ->mergeBindings($sub->getQuery()) 
    ->count();

you have converted the first sub query to sql string, BUT the second query does not know any thing about your first sub query binding which in this example the value 1

so we need to merge the binding from the first sub query into the last query so that the last query when executes it will know the value 1 and binds it to the where clause in replace of "?", and your final executed query will be something like this

(SELECT count(*) from abc where type = 1 GROUP BY ...) as sub

and thats it the use of mergeBindings() method

i hope this makes things clear for your question.

thanks,

Ahmed Saad
  • 159
  • 1
  • 5