where('id', 1)->toSql(); The sql obtained The statement is: select * from...."/> where('id', 1)->toSql(); The sql obtained The statement is: select * from....">

Home  >  Article  >  PHP Framework  >  How to get the sql statement with parameters using toSql in laravel

How to get the sql statement with parameters using toSql in laravel

藏色散人
藏色散人forward
2020-02-02 19:29:354485browse

How to get the sql statement with parameters using toSql in laravel

By default, the parameters in the sql obtained by toSql are replaced by "?", as follows:

DB::table('user')->where('id', 1)->toSql();

The sql statement obtained is:

select * from `tb_user` where `id` = ?

Sometimes we want to get specific statements, we can use the builder's getBindings method:

$builder = DB::table('user')->where('id', 1);
$bindings = $builder->getBindings();
$sql = str_replace('?', '%s', $builder->toSql());
$sql = sprintf($sql, ...$bindings);
dd($sql);

The obtained sql statement is:

select * from `tb_user` where `id` = 1

If you use it frequently, you can consider using the Builder The macro method is added to the Builder:

\Illuminate\Database\Query\Builder::macro('sql', function () {
    $bindings = $this->getBindings();
    $sql = str_replace('?', '%s', $this->toSql());
 
    return sprintf($sql, ...$bindings);
});
dd(DB::table('user')->where('id', 1)->sql());

For more technical articles related to the laravel framework, please visit the laravel tutorial column!

The above is the detailed content of How to get the sql statement with parameters using toSql in laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete