| 1 | <?php |
||
| 11 | trait MultilingualTrait |
||
| 12 | { |
||
| 13 | /** |
||
| 14 | * @var string the name of the lang field of the translation table. Default to 'language'. |
||
| 15 | */ |
||
| 16 | public $languageField = 'language'; |
||
| 17 | |||
| 18 | /** |
||
| 19 | * Scope for querying by languages |
||
| 20 | * @param $language |
||
| 21 | * @param $abridge |
||
| 22 | * @return $this |
||
| 23 | */ |
||
| 24 | 4 | public function localized($language = null, $abridge = true) |
|
| 25 | { |
||
| 26 | 4 | if (!$language) |
|
| 27 | 4 | $language = Yii::$app->language; |
|
| 28 | |||
| 29 | 4 | if (!isset($this->with['translations'])) { |
|
| 30 | 4 | $this->with(['translation' => function ($query) use ($language, $abridge) { |
|
| 31 | 3 | $query->where([$this->languageField => $abridge ? substr($language, 0, 2) : $language]); |
|
| 32 | 4 | }]); |
|
| 33 | 4 | } |
|
| 34 | |||
| 35 | 4 | return $this; |
|
| 36 | } |
||
| 37 | |||
| 38 | /** |
||
| 39 | * Scope for querying by all languages |
||
| 40 | * @return $this |
||
| 41 | */ |
||
| 42 | 6 | public function multilingual() |
|
| 43 | { |
||
| 44 | 6 | if (isset($this->with['translation'])) { |
|
| 45 | 1 | unset($this->with['translation']); |
|
| 46 | 1 | } |
|
| 47 | 6 | $this->with('translations'); |
|
| 48 | 6 | return $this; |
|
| 49 | } |
||
| 50 | |||
| 51 | /** |
||
| 52 | * @return \yii\db\ActiveQuery |
||
| 53 | */ |
||
| 54 | abstract public function with(); |
||
| 55 | } |
||
| 56 |