Monday, November 5, 2018

50+ Useful Laravel Quries (Part - 2)

17. HOW TO PRINT RAW SQL QUERY IN LARAVEL

Example #1
$sql = exampleModel::where('name', '=', 'Arindam Roy')
->orWhere('age', '>=', '20')->toSql();

echo $sql;

OUTPUT :
"select * from `example_table` where `name` = ? or `age` >= ?"

Example #2 (Grouping) (Nested where grouping)
$sql = DB::table('example_table'); $sql = $sql->where( function($sql) { $sql->where('name', 'like', '%ari%'); $sql->where('age', '>', '30'); });
$sql = $sql->orWhere( function($sql) {

        $sql->where('salary', '<', '25000');
        $sql->where('age', '>', '30');
});
$sql = $sql->toSql();
echo $sql;
OUTPUT :
"select * from `example_table` where (`name` like ? and `age` > ?) or (`salary` < ? and `age` > ?)"

Example #3 (More nested query) 
$sql = DB::table('example_table'); $sql = $sql->where( function($sql) { $sql->where('name', 'like', '%ari%'); $sql->where('age', '>', '30'); }); $sql = $sql->orWhere( function($sql) { $sql->where('salary', '<', '50000'); $sql = $sql->where( function($sql) { $sql = $sql->where('id', '>', '2'); $sql = $sql->orWhere('id', '=', '5'); }); }); $sql = $sql->toSql(); echo $sql;
OUTPUT :
"select * from `example_table` where (`name` like ? and `age` > ?) or (`salary` < ? and (`id` > ? or `id` = ?))"

No comments:

Post a Comment