Skip to content

Commit 4c0e015

Browse files
committed
Improve order scope tests
1 parent 07286b9 commit 4c0e015

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

src/Translatable/Traits/Scopes.php

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,14 +57,13 @@ public function scopeOrderByTranslation(Builder $query, string $translationField
5757

5858
return $query
5959
->with('translations')
60-
->select($table.'.*')
60+
->select("{$table}.*")
6161
->leftJoin($translationTable, function (JoinClause $join) use ($translationTable, $localeKey, $table, $keyName) {
6262
$join
63-
->on($translationTable.'.'.$this->getTranslationRelationKey(), '=', $table.'.'.$keyName)
64-
->where($translationTable.'.'.$localeKey, $this->locale());
63+
->on("{$translationTable}.{$this->getTranslationRelationKey()}", '=', "{$table}.{$keyName}")
64+
->where("{$translationTable}.{$localeKey}", $this->locale());
6565
})
66-
->orderByRaw("CASE WHEN {$translationTable}.{$translationField} = '{$this->locale()}' THEN 1 ELSE 2 END")
67-
->orderBy("{$translationTable}.{$localeKey}", $sortMethod);
66+
->orderBy("{$translationTable}.{$translationField}", $sortMethod);
6867
}
6968

7069
public function scopeOrWhereTranslation(Builder $query, string $translationField, $value, ?string $locale = null)

tests/ScopesTest.php

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
<?php
22

33
use Astrotomic\Translatable\Test\Model\Country;
4+
use Astrotomic\Translatable\Test\Model\Food;
45
use Astrotomic\Translatable\Test\Model\Vegetable;
56

67
final class ScopesTest extends TestsBase
@@ -215,8 +216,15 @@ public function test_orderByTranslation_sorts_by_key_desc()
215216

216217
public function test_orderByTranslation_sorts_by_key_asc_even_if_locale_is_missing()
217218
{
218-
App::setLocale('ca');
219-
$result = Country::orderByTranslation('name')->count();
220-
$this->assertSame(4, $result);
219+
Food::create(['en' => ['name' => 'Potatoes'],'fr' => ['name' => 'Pommes de Terre']]);
220+
Food::create(['en' => ['name' => 'Strawberries'],'fr' => ['name' => 'Fraises']]);
221+
Food::create([]);
222+
223+
$orderInEnglish = Food::with('translations')->orderByTranslation('name')->get();
224+
$this->assertEquals([null, 'Potatoes', 'Strawberries'], $orderInEnglish->pluck('name')->toArray());
225+
226+
App::setLocale('fr');
227+
$orderInFrench = Food::with('translations')->orderByTranslation('name', 'desc')->get();
228+
$this->assertEquals(['Pommes de Terre', 'Fraises', null], $orderInFrench->pluck('name')->toArray());
221229
}
222230
}

0 commit comments

Comments
 (0)