Skip to content

Instantly share code, notes, and snippets.

@bolechen
Last active December 24, 2020 06:21
Show Gist options
  • Save bolechen/c0dc76ae0429f090d4a00a264f2c30f6 to your computer and use it in GitHub Desktop.
Save bolechen/c0dc76ae0429f090d4a00a264f2c30f6 to your computer and use it in GitHub Desktop.
easy way to debut sql like this: `User::where(xxx)->toRawSql();`
<?php
private function bootSupportMacros(): self
{
\Illuminate\Database\Query\Builder::macro('toRawSql', function (): string {
/** @var \Illuminate\Database\Query\Builder $builder */
$builder = $this;
return array_reduce($builder->getBindings(), static function ($sql, $binding) {
return preg_replace('/\?/', is_numeric($binding) ? $binding : "'".$binding."'", $sql, 1);
}, $builder->toSql());
});
\Illuminate\Database\Eloquent\Builder::macro('toRawSql', function (): string {
/** @var \Illuminate\Database\Eloquent\Builder $builder */
$builder = $this;
return $builder->getQuery()->toRawSql();
});
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment