anacreation / translatable
翻译模型
dev-develop
2018-06-20 06:02 UTC
Requires
- php: >=7.1.0
- laravel/framework: 5.5.*
This package is auto-updated.
Last update: 2024-09-24 21:44:46 UTC
README
此插件为 Eloquent Model
添加翻译功能
安装
composer require anacreation/translatable
使用此插件的 Eloquent 模型
namespace App; use Anacreation\Translatable\traits\TranslatableTrait; use Illuminate\Database\Eloquent\Model; class Product extends Model { use TranslatableTrait; }
可以使用以下 API
使用方法
创建和更新翻译
createModelWithTranslations( array $attributes = [], array $content): Model
$content
有一个预设的格式
$content = [
"language_code_1"=>[
"attribute_1" => "value 1",
"attribute_2" => "value 2",
"attribute_3" => "value 3",
],
"language_code_2"=>[
"attribute_1" => "value 4",
"attribute_2" => "value 5",
"attribute_3" => "value 6",
]
]
$newModel = Model::createModelWithTranslations($attributes, $content);
它创建一个模型实例并保存内容
updateTranslations(array $content): void
无论是创建新的语言翻译还是更新现有的翻译,只需简单调用此函数。$content 结构与上面相同。
检索翻译
如果你有一个如上所示的带有翻译的模型。
那么你可以
$mode->attribute_1;
这将自动根据你当前的地区设置检索翻译。
app()->getLocale();
回退
默认回退设置为 false
,如果内容为 null
则无回退。
回退系统非常简单。如果你设置了配置 fallback_locale
并将 Eloquent 模型回退设置为 true
$model->fallback = true;
那么如果特定属性的翻译为 null
,它将尝试获取回退地区的翻译。
检索所有翻译
$translation_array = $model->translatables;
这将返回一个数组,如上所示。翻译数组结构如下
[
"language_code_1"=>[
"attribute_1" => "value 1",
"attribute_2" => "value 2",
],
"language_code_2"=>[
"attribute_1" => "value 3",
"attribute_2" => "value 4",
]
]
删除翻译
deleteTranslatableAttribute( string $key, string $locale = null ): void
这将删除所有或特定翻译的特定属性。如果原始翻译如下
[
"language_code_1"=>[
"attribute_1" => "value 1",
"attribute_2" => "value 2",
],
"language_code_2"=>[
"attribute_1" => "value 3",
"attribute_2" => "value 4",
]
]
我们调用
$model->deleteTranslatableAttribute("attribute_2");
翻译将变为
[
"language_code_1"=>[
"attribute_1" => "value 1",
],
"language_code_2"=>[
"attribute_1" => "value 3",
]
]
如果我们调用
$model->deleteTranslatableAttribute("attribute_2", "language_code_2");
结果将如下
[
"language_code_1"=>[
"attribute_1" => "value 1",
"attribute_2" => "value 2",
],
"language_code_2"=>[
"attribute_1" => "value 3",
]
]
deleteTranslatableWithLocale(string $locale ): void
这将删除指定地区的所有翻译。如果我们调用
$model->deleteTranslatableWithLocale("language_code_2");
结果将如下
[
"language_code_1"=>[
"attribute_1" => "value 1",
"attribute_2" => "value 2",
]
]