You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

61 lines
1.4 KiB

<?php
/**
* Created by Error202
* Date: 26.08.2018
*/
namespace core\components;
use yii\db\ActiveQuery;
use Yii;
/**
* Translate trait.
* Modify ActiveRecord query for translate support
*
* @mixin ActiveQuery
*/
trait LanguageTranslateTrait
{
/**
* @var string the name of the lang field of the translation table. Default to 'language'.
*/
public string $languageField = 'language';
/**
* Scope for querying by languages
*
* @param string|null $language
* @param bool $abridge
*
* @return $this
*/
public function localized(string $language = null, bool $abridge = true): static
{
$language = $language ?: Yii::$app->language;
if (!isset($this->with['translations'])) {
$this->with([
'translation' => function ($query) use ($language, $abridge) {
/** @var ActiveQuery $query */
$query->where([$this->languageField => $abridge ? substr($language, 0, 2) : $language]);
}
]);
}
return $this;
}
/**
* Scope for querying by all languages
* @return $this
*/
public function multilingual(): static
{
if (isset($this->with['translation'])) {
unset($this->with['translation']);
}
$this->with('translations');
return $this;
}
}