I have a complex query created by a few conditions, and I would like to get the final SQL query from the builder object is about to execute. Can I do that?
DB::QueryLog() works only after you execute the query using $builder->get() . If you want to get the raw query before or without executing the query, you can use the $builder->toSql() method.
If you write your query in Tinkerwell anyway, you can highlight the Eloquent query and press Cmd+Shift+R (or Ctrl+Shift+R if you are on Windows) and Tinkerwell profiles the query directly in the editor. You see all executed queries, the time that the query run, the memory consumption and even the peak for your memory.
On the other hand, RawQuery serves as an escape hatch where you can build your own SQL query at runtime but still use Room to convert it into objects. RawQuery methods must return a non-void type. If you want to execute a raw query that does not return any value, use RoomDatabase#query methods.
You can get it doing:
$query = DB::table('brands') ->join('products','a','=','c') ->whereNull('whatever'); echo $query->toSql();
But Laravel will not show you parameters in your query, because they are bound after preparation of the query.
So you can also do:
print_r( $query->getBindings() );
For debugging this might come quite handy as it returns the SQL with the bindings, so you can instantly put it into the database console.
/** * Combines SQL and its bindings * * @param \Eloquent $query * @return string */ public static function getEloquentSqlWithBindings($query) { return vsprintf(str_replace('?', '%s', $query->toSql()), collect($query->getBindings())->map(function ($binding) { return is_numeric($binding) ? $binding : "'{$binding}'"; })->toArray()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With