Showing posts with label db raw. Show all posts
Showing posts with label db raw. Show all posts

Saturday, February 11, 2017

Raw Queries in Laravel | Get Sql Query And Bindings From Laravel Eloquent Query Builder | Execute Raw Query With Parameters

Laravel has a strong query builder to build queries. It is as much powerful as we need. But sometimes we need to execute raw sql using Laravel. Below is a code snippet to execute raw sql queries using Laravel. The below code will return some results.


$results = DB::select( DB::raw("SELECT * FROM table_name WHERE field_id = :field_id"),
array(
    'field_id' => 5,
));

If you dont need to return results and only need to do some statement level queries then do the following:

DB::statement("UPDATE USER SET STATUS='ACTIVE' WHERE ID=1;");


You can get Raw SQL and Bindings from Laravel eloquent query builder:

$query = DB::table("my_table")->where("id", $id);
echo $query->toSql();
print_r($query->getBindings());


Laravel group concat operation

It is important to get some concat value. You can use GROUP_CONCAT in Laravel easily. Below is a code snippet to do the trick:


$result = DB::table('table_name')
       ->select(DB::raw('group_concat(field_name) as field_name_alias'))
       ->where('condition_field', '=', $condition_value )
       ->first();