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

Commit

Permalink
Don't force translations lazy-load on save
Browse files Browse the repository at this point in the history
Prevent N+1 queries when creating/updating
non-translated model attributes.

Don't lazy-load the 'translations'
relationship when saving the base
translated model.
  • Loading branch information
derekmd committed Nov 3, 2018
1 parent cf6c8dc commit 98cac13
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Translatable/Translatable.php
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,11 @@ protected function getLocaleSeparator()
protected function saveTranslations()
{
$saved = true;

if (! $this->relationLoaded('translations')) {
return $saved;
}

foreach ($this->translations as $translation) {
if ($saved && $this->isTranslationDirty($translation)) {
if (! empty($connectionName = $this->getConnectionName())) {
Expand Down
23 changes: 23 additions & 0 deletions tests/TranslatableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,29 @@ public function test_it_saves_translations_with_mutator()
$this->assertEquals('5678', $translation->name);
}

public function test_it_does_not_lazy_load_translations_when_updating_non_translated_attributes()
{
DB::enableQueryLog();

$country = Country::create(['code' => 'be']);
$this->assertFalse($country->relationLoaded('translations'));
$this->assertCount(1, DB::getQueryLog());

DB::flushQueryLog();

$country->update(['code' => 'de']);
$this->assertFalse($country->relationLoaded('translations'));
$this->assertCount(1, DB::getQueryLog());

DB::flushQueryLog();

$country->update(['name' => 'Germany']);
$this->assertTrue($country->relationLoaded('translations'));
$this->assertCount(2, DB::getQueryLog());

DB::disableQueryLog();
}

public function test_it_uses_default_locale_to_return_translations()
{
$country = Country::whereCode('gr')->first();
Expand Down

0 comments on commit 98cac13

Please sign in to comment.