skelag/laravel-translatable-model

v0.3.3 2022-04-26 08:05 UTC

This package is auto-updated.

Last update: 2024-09-29 05:57:11 UTC


README

该库允许使用 Eloquent 模型来方便地存储翻译

安装

使用作曲器

composer require skelag/laravel-translatable-model

使用

配置表和模型

要使用具有翻译的模型,需要创建一个包含主实体的表

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateBooksTable extends Migration
{
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->id();

            $table->date('written_at')->default(now());

            $table->timestamps();
        });
        
        $this->translates('books', ['author' => 'string', 'name' => 'string']);
    }

    public function down()
    {
        $this->dropTranslates('books');
        Schema::dropIfExists('books');
    }
}

然后简单地从主模型继承 TranslatableModel

namespace App\Models;

use SkelaG\LaravelTranslatableModel\Models\TranslatableModel;

class Book extends TranslatableModel
{
}

翻译模型继承 TranslationModel,指定可填充字段和可翻译字段(必须是可填充的)

namespace App\Models;

use SkelaG\LaravelTranslatableModel\Models\TranslationModel;

class BookTranslation extends TranslationModel
{
    protected array $translatable = ['name', 'author'];
}

使用模型

创建

App::setLocale('ru');
$book = \App\Models\Book::create([
    'written_at' => \Carbon\Carbon::parse('1833-01-01'),
    'author' => 'Александр Сергеевич Пушкин',
    'name' => 'Евгений Онегин'
]);

App::setLocale('ru');
$book = new \App\Models\Book();
$book->author = 'Александр Сергеевич Пушкин';
$book->name = 'Евгений Онегин';
$book->save();

添加翻译

需要设置正确的区域设置并更新模型

App::setLocale('en');
$book = \App\Models\Book::first();
$book->update(['author' => 'Alexander Sergeyevich Pushkin', 'name' => 'Eugene Onegin']);

App::setLocale('en');
$book = \App\Models\Book::first();
$book->author = 'Alexander Sergeyevich Pushkin';
$book->name = 'Eugene Onegin';

更新翻译中的值也是这样进行的