Skip to content

Commit

Permalink
support datetime value
Browse files Browse the repository at this point in the history
  • Loading branch information
PyaeSoneAungRgn committed Feb 10, 2023
1 parent d46f264 commit 1288b7f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
19 changes: 12 additions & 7 deletions src/ToRawSqlServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace PyaeSoneAung\ToRawSql;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;
use Spatie\LaravelPackageTools\Package;
Expand All @@ -12,13 +13,17 @@ class ToRawSqlServiceProvider extends PackageServiceProvider
public function boot(): void
{
Builder::macro('toRawSql', function (): string {
/** @var \Illuminate\Database\Eloquent\Builder $this */
$bindings = [];
foreach ($this->getBindings() as $value) {
if (is_string($value)) {
$bindings[] = "'{$value}'";
} else {
$bindings[] = $value;
/**
* @var \Illuminate\Database\Eloquent\Builder $this
*/
$bindings = $this->getBindings();
foreach ($bindings as $key => $value) {
if ($value instanceof DateTimeInterface) {
$bindings[$key] = "'{$value->format('Y-m-d H:i:s')}'";
} elseif (is_bool($value)) {
$bindings[$key] = (int) $value;
} elseif (is_string($value)) {
$bindings[$key] = "'{$value}'";
}
}

Expand Down
12 changes: 11 additions & 1 deletion tests/ToRawSqlTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,16 @@
$query->where('name', 'Abigail')
->where('votes', '>', 50);
})
->where(
'created_at',
now()
->setYear(2023)
->setMonth(02)
->setDay(10)
->setHour(13)
->setMinute(22)
->setSecond(38)
)
->toRawSql()
)->toBe("select * from `users` where `votes` > 100 or (`name` = 'Abigail' and `votes` > 50)");
)->toBe("select * from `users` where `votes` > 100 or (`name` = 'Abigail' and `votes` > 50) and `created_at` = '2023-02-10 13:22:38'");
});

0 comments on commit 1288b7f

Please sign in to comment.