creocoder / yii2-translateable

The translateable behavior for the Yii framework.
Other
102 stars 23 forks source link

Updating translations causes duplicate relations on main object #14

Open zebraf1 opened 6 years ago

zebraf1 commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

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