Skip to content
This repository has been archived by the owner on Jun 18, 2019. It is now read-only.

added orderByTranslation scope #504

Merged
merged 10 commits into from
Jul 24, 2018
28 changes: 28 additions & 0 deletions src/Translatable/Translatable.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Dimsav\Translatable\Exception\LocalesNotDefinedException;
Expand Down Expand Up @@ -677,6 +678,33 @@ public function scopeOrWhereTranslationLike(Builder $query, $key, $value, $local
});
}

/**
* This scope sorts results by the given translation field.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $key
* @param string $sortmethod
*
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function scopeOrderByTranslation(Builder $query, $key, $sortmethod = 'asc')
{
$translationTable = $this->getTranslationsTable();
$localeKey = $this->getLocaleKey();
$table = $this->getTable();
$keyName = $this->getKeyName();

return $query
->join($translationTable, function (JoinClause $join) use ($translationTable, $localeKey, $table, $keyName) {
$join
->on($translationTable.'.'.$this->getRelationKey(), '=', $table.'.'.$keyName)
->where($translationTable.'.'.$localeKey, $this->locale());
})
->orderBy($translationTable.'.'.$key, $sortmethod)
->select($table.'.*')
->with('translations');
}

/**
* @return array
*/
Expand Down
12 changes: 12 additions & 0 deletions tests/ScopesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -165,4 +165,16 @@ public function test_whereTranslationLike_filters_by_translation_and_locale()
$this->assertSame(1, $result->count());
$this->assertSame('gr', $result->first()->code);
}

public function test_orderByTranslation_sorts_by_key_asc()
{
$result = Country::orderByTranslation('name')->get();
$this->assertSame(2, $result->first()->id);
}

public function test_orderByTranslation_sorts_by_key_desc()
{
$result = Country::orderByTranslation('name', 'desc')->get();
$this->assertSame(1, $result->first()->id);
}
}