Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updating translations causes duplicate relations on main object #14

Open
zebraf1 opened this issue Feb 1, 2018 · 2 comments
Open

Updating translations causes duplicate relations on main object #14

zebraf1 opened this issue Feb 1, 2018 · 2 comments

Comments

@zebraf1
Copy link

zebraf1 commented Feb 1, 2018

I have a model with translatable behaviour and

    public function getTranslations()
    {
        return $this->hasMany(ModelI18n::className(), ['id' => 'id']);
    }

When I do:

$translation = $mainModel->translate('eng');
$translation->name = 'New name';
$mainModel->save();

$mainModel->translations has duplicate entries

This code loops over existing translations and calls link() which causes duplicate related objects:

// TranslateableBehavior.php
    /**
     * @return void
     */
    public function afterSave()
    {
        /* @var ActiveRecord $translation */
        foreach ($this->owner->{$this->translationRelation} as $translation) {
            $this->owner->link($this->translationRelation, $translation);
        }
    }

If $this->owner->{$this->translationRelation} returns related objects, they are already linked. When you create new translations, you have to link them yourself.

@zebraf1
Copy link
Author

zebraf1 commented Feb 1, 2018

My current fix is to extend this behavior class and extend afterSave method:

    public function afterSave()
    {
        $translations = $this->owner->{$this->translationRelation};
        $this->owner->populateRelation($this->translationRelation, []); // clear related to avoid double relations

        /* @var ActiveRecord $translation */
        foreach ($translations as $translation) {
            $this->owner->link($this->translationRelation, $translation);
        }
    }

@zebraf1
Copy link
Author

zebraf1 commented Feb 2, 2018

Note that your class name has a spelling error. Translateable is not a correct word, see https://en.wiktionary.org/wiki/translatable

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant