rkit / translation-behavior-yii2
Yii2 的翻译行为
2.0.0
2018-08-07 16:14 UTC
Requires
- yiisoft/yii2: ^2.0.0, !=2.0.15.1
Requires (Dev)
- phpunit/dbunit: ^4.0
- phpunit/phpunit: ^7.2
- squizlabs/php_codesniffer: ^3.3
This package is not auto-updated.
Last update: 2024-09-23 07:59:50 UTC
README
需求
PHP 7
安装
composer require rkit/translation-behavior-yii2
配置
例如,我们有一个 Post
模型,我们想要添加翻译功能。
让我们开始吧。
- 为翻译添加一个
post_translation
表和一个PostTranslation
模型
$this->createTable('{{%post_translation}}', [ 'id' => $this->primaryKey(), 'post_id' => $this->integer()->notNull()->defaultValue(0), 'language' => $this->string(2)->notNull()->defaultValue(''), 'title' => $this->string()->notNull()->defaultValue(''), ]);
- 将
TranslationBehavior
行为添加到Post
模型
public function behaviors() { return [ 'translationBehavior' => [ 'class' => 'rkit\translation\behavior\TranslationBehavior', 'relationOne' => 'translation', 'relationMany' => 'translations', 'languageAttribute' => 'language', 'defaultLanguage' => 'en', 'attributes' => [ // attributes for translation 'title', ], ], ]; }
- 添加
translation
和translations
关联(参见行为中的relationOne
和relationMany
选项)
/** * @return \yii\db\ActiveQuery */ public function getTranslation() { return $this ->hasOne(PostTranslation::class, ['post_id' => 'id']) ->andWhere(['language' => \Yii::$app->language]); } /** * @return \yii\db\ActiveQuery */ public function getTranslations() { return $this->hasMany(PostTranslation::class, ['post_id' => 'id']); }
使用方法
加载翻译
$model = new Post(); $model->loadTranslations([ 'en' => ['title' => 'example'], 'ru' => ['title' => 'пример'], ]); $model->save();
获取翻译
对于当前语言
$model = Post::find()->with('translation')->where(['id' => $id])->one(); echo $model->title;
所有翻译
$model = Post::find()->with('translations')->where(['id' => $id])->one(); echo $model->translate('en')->title; echo $model->translate('ru')->title;
移除翻译
$model = new Post(); $model->loadTranslations([]); $model->save();
测试
编码规范
- PHP Code Sniffer (phpcs.xml)