Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what the meaning mergeBindings in laravel

Tags:

php

mysql

laravel

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

like image 895
b4dQuetions Avatar asked Dec 08 '15 03:12

b4dQuetions


People also ask

What is Find_in_set in Laravel?

FIND_IN_SET method is predefine method of MySQL. In Laravel, You will use whereRaw() method to write your own raw SQL queries. So you can use “find_in_set” method with whereRaw() in Laravel.

What is DB :: Raw Laravel?

DB::raw() is used to make arbitrary SQL commands which aren't parsed any further by the query builder. They therefore can create a vector for attack via SQL injection.

What is DB :: statement in Laravel?

Instead, I use DB::statement($queryString); to insert data into database. $queryString is built from input variables concatenated with pre-built SQL statement. Here is the code from my controler (note that actual query is more complex, this is just an example): /** * Store a newly created resource in storage.

What is leftJoin in Laravel?

The leftJoin() method is part of a query builder that is used to carry out the left joining table operation in Laravel.


1 Answers

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,

like image 50
Ahmed Saad Avatar answered Sep 21 '22 06:09

Ahmed Saad