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

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

藏色散人
Release: 2020-02-02 19:29:35
forward
4585 people have browsed it

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();
Copy after login

The sql statement obtained is:

select * from `tb_user` where `id` = ?
Copy after login

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);
Copy after login

The obtained sql statement is:

select * from `tb_user` where `id` = 1
Copy after login

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());
Copy after login

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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template