Home >Backend Development >PHP Tutorial >How Do I Get the Raw SQL Query from a Query Builder?
Getting Raw SQL Query from Query Builder
Query builders are a powerful tool for constructing database queries in a convenient and expressive syntax. However, there may be instances when you need to access the underlying SQL query generated by the query builder.
To obtain the raw SQL query string, use the toSql() method on a QueryBuilder instance. The following example demonstrates how to use it:
$queryBuilder = DB::table('users'); $sql = $queryBuilder->toSql(); // "select * from `users`"
In this example, the $sql variable will contain the following SQL query:
select * from `users`
This method is more convenient than using event listeners and provides an easy way to inspect the query as it is being built.
Note: The toSql() method can be used with both query builder and Eloquent models. However, you should use toSql() instead of first() or get() to obtain the SQL query without executing it.
The above is the detailed content of How Do I Get the Raw SQL Query from a Query Builder?. For more information, please follow other related articles on the PHP Chinese website!