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

Commit

Permalink
Merge pull request #168 from dimsav/where-translation-scope
Browse files Browse the repository at this point in the history
Added whereTranslation() scope
  • Loading branch information
dimsav committed Oct 21, 2015
2 parents f368f08 + 775b2ef commit 5cf6baa
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
## Version History

### v.5.3

- Added whereTranslation() scope.

### v.5.2

- Added option to override default locale #158
Expand Down
3 changes: 3 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,9 @@ Country::withTranslation()->get();
// ['id' => 2, 'name' => 'Belgium']
// ]
Country::listsTranslations('name')->get()->toArray();

// Filters countries by checking the translation against the given value
Country::whereTranslation('name', 'Greece')->first();
```

### Magic properties
Expand Down
22 changes: 22 additions & 0 deletions src/Translatable/Translatable.php
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,28 @@ public function scopeWithTranslation(Builder $query)
}]);
}


/**
* This scope filters results by checking the translation fields.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $key
* @param string $value
* @param string $locale
*
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function scopeWhereTranslation($query, $key, $value, $locale = null)
{
return $query->whereHas('translations', function ($query) use ($key, $value, $locale) {
$query->where($this->getTranslationsTable().'.'.$key, $value);
if ($locale) {
$query->where($this->getTranslationsTable().'.'.$this->getLocaleKey(), $locale);
}
});
}


/**
* @return array
*/
Expand Down
18 changes: 18 additions & 0 deletions tests/ScopesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,22 @@ public function test_scope_withTranslation_with_fallback()
$this->assertSame('Griechenland', $loadedTranslations[1]['name']);
}

public function test_whereTranslation_filters_by_translation()
{
/** @var Country $country */
$country = Country::whereTranslation('name', 'Greece')->first();
$this->assertSame('gr', $country->code);
}

public function test_whereTranslation_filters_by_translation_and_locale()
{
Country::create(['code' => 'some-code', 'name' => 'Griechenland']);

/** @var Country $country */
$this->assertSame(2, Country::whereTranslation('name', 'Griechenland')->count());

$result = Country::whereTranslation('name', 'Griechenland', 'de')->get();
$this->assertSame(1, $result->count());
$this->assertSame('gr', $result->first()->code);
}
}

0 comments on commit 5cf6baa

Please sign in to comment.