-
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(Database): Add OrderByValuesScope for ordering by values in give…
…n order
- Loading branch information
Showing
2 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace LaraStrict\Database\Scopes; | ||
|
||
use Illuminate\Database\Eloquent\Builder; | ||
use Illuminate\Database\Eloquent\Model; | ||
|
||
class OrderByValuesScope extends AbstractScope | ||
{ | ||
/** | ||
* @param array<string|int> $values | ||
*/ | ||
public function __construct( | ||
private readonly array $values, | ||
private readonly string $column | ||
) { | ||
} | ||
|
||
public function apply(Builder $builder, Model $model): void | ||
{ | ||
$placeholders = array_map(static fn () => '?', $this->values); | ||
|
||
$builder->orderByRaw( | ||
'FIELD(`' . $this->column . '`, ' . implode(', ', $placeholders) . ') DESC', | ||
$this->values | ||
); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace Tests\LaraStrict\Feature\Database\Scopes; | ||
|
||
use Illuminate\Database\Eloquent\SoftDeletingScope; | ||
use LaraStrict\Database\Scopes\OrderByValuesScope; | ||
use Tests\LaraStrict\Feature\Database\Models\Test; | ||
use Tests\LaraStrict\Feature\TestCase; | ||
|
||
class OrderByValuesScopeTest extends TestCase | ||
{ | ||
public function testApply(): void | ||
{ | ||
$query = Test::query() | ||
->withoutGlobalScope(new SoftDeletingScope()) | ||
->withGlobalScope('test', new OrderByValuesScope(['1', 2, 's33'], Test::AttributeTest)); | ||
|
||
$this->assertEquals( | ||
expected: 'select * from "tests" order by FIELD(`test`, ?, ?, ?) DESC', | ||
actual: $query->toSql() | ||
); | ||
|
||
$this->assertEquals(expected: ['1', 2, 's33'], actual: $query->getBindings()); | ||
} | ||
} |