creocoder\translateable\TranslateableBehavior::getTranslation PHP Method

getTranslation() public method

Returns the translation model for the specified language.
public getTranslation ( string | null $language = null ) : ActiveRecord
$language string | null
return yii\db\ActiveRecord
    public function getTranslation($language = null)
    {
        if ($language === null) {
            $language = Yii::$app->language;
        }
        /* @var ActiveRecord[] $translations */
        $translations = $this->owner->{$this->translationRelation};
        foreach ($translations as $translation) {
            if ($translation->getAttribute($this->translationLanguageAttribute) === $language) {
                return $translation;
            }
        }
        /* @var ActiveRecord $class */
        $class = $this->owner->getRelation($this->translationRelation)->modelClass;
        /* @var ActiveRecord $translation */
        $translation = new $class();
        $translation->setAttribute($this->translationLanguageAttribute, $language);
        $translations[] = $translation;
        $this->owner->populateRelation($this->translationRelation, $translations);
        return $translation;
    }

Usage Example

示例#1
0
 /**
  * @inherited
  */
 public function getTranslation($language = null)
 {
     if ($language === null) {
         $language = Lang::getCurrent()->id;
     }
     return parent::getTranslation($language);
 }