卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章73687本站已运行432

使用自动加载翻译在 Laravel 中构建多态可翻译模型

使用自动加载翻译在 laravel 中构建多态可翻译模型

处理多语言内容时,将翻译存储在 json 列中通常比每个属性的单独行更有效。这种方法将翻译整合到单个列中,简化了数据管理和检索。

设置翻译系统

我们将增强翻译模型和表,以使用 json 列来存储翻译。这将涉及更新表架构并修改 translatable 特征以处理 json 数据。

第 1 步:创建翻译表迁移

如果翻译表尚不存在,则创建一个新的迁移:

php artisan make:migration create_translations_table

第2步:定义表结构

在database/migrations中打开生成的迁移文件。对于新表,定义如下:

use illuminatedatabasemigrationsmigration;
use illuminatedatabaseschemablueprint;
use illuminatesupportfacadesschema;

class createtranslationstable extends migration
{
    public function up()
    {
        schema::create('translations', function (blueprint $table) {
            $table->id();
            $table->string('locale'); // stores the locale, e.g., 'en', 'fr'
            $table->string('translatable_type'); // stores the related model type, e.g., 'post', 'product'
            $table->unsignedbiginteger('translatable_id'); // stores the id of the related model
            $table->json('translations'); // stores all translations as a json object
            $table->timestamps();
        });
    }

    public function down()
    {
        schema::dropifexists('translations');
    }
}

第 3 步:运行迁移
将迁移应用到您的数据库:

php artisan migrate

第四步:创建翻译模型

接下来,创建翻译模型来处理多态关系:

php artisan make:model translation

在translation模型中,定义多态关系:

class translation extends model
{
    protected $fillable = ['locale', 'translatable_type', 'translatable_id', 'translations'];

    protected $casts = [
        'translations' => 'array',
    ];

    public function translatable()
    {
        return $this->morphto();
    }
}

使用 json 存储实现可翻译特征

为了使翻译处理可在多个模型中重用,我们将创建一个 translatable 特征,它将根据用户选择的区域设置自动加载翻译内容。此外,如果所选语言环境没有可用的翻译,我们将添加一个后备机制来从默认语言环境加载内容。

第 1 步:使用 json 处理创建可翻译特征

namespace apptraits;

use appmodelstranslation;
use illuminatesupportfacadesapp;

trait translatable
{
    public static function boottranslatable()
    {
        static::retrieved(function ($model) {
            $model->loadtranslations();
        });
    }

    public function translations()
    {
        return $this->morphmany(translation::class, 'translatable');
    }

    public function loadtranslations()
    {
        $locale = app::getlocale();
        $defaultlocale = config('app.default_locale', 'en'); // fallback to the default locale

        // try to load translations for the current locale
        $translation = $this->translations()->where('locale', $locale)->first();

        if (!$translation && $locale !== $defaultlocale) {
            // if no translations are found for the current locale, fallback to the default locale
            $translation = $this->translations()->where('locale', $defaultlocale)->first();
        }

        if ($translation) {
            $translations = $translation->translations;
            foreach ($translations as $key => $value) {
                $this->{$key} = $value;
            }
        }
    }

    public function addtranslations(array $translations, $locale = null)
    {
        $locale = $locale ?? app::getlocale();
        return $this->translations()->updateorcreate(
            ['locale' => $locale],
            ['translations' => $translations]
        );
    }
}

第 2 步:将可翻译特征应用于您的模型
将 translatable 特征添加到任何需要翻译支持的模型中。

namespace appmodels;

use apptraitstranslatable;
use illuminatedatabaseeloquentmodel;

class post extends model
{
    use translatable;

    protected $fillable = ['title', 'content'];
}

示例:创建翻译模型

将翻译添加为 json 对象:

$post = post::create(['title' => 'default title', 'content' => 'default content']);

// adding translations
$post->addtranslations([
    'title' => 'hello world',
    'content' => 'welcome to our website'
], 'en');

$post->addtranslations([
    'title' => 'bonjour le monde',
    'content' => 'bienvenue sur notre site web'
], 'fr');

检索翻译模型

当您检索 post 模型时,它将根据当前语言环境自动加载翻译后的内容,或者在必要时回退到默认语言环境:

app::setlocale('fr');
$post = post::find(1);
echo $post->title; // displays "bonjour le monde" if french translation exists

app::setlocale('es');
$post = post::find(1);
echo $post->title; // displays "hello world" as it falls back to the english translation

在视图中显示翻译内容

在 blade 视图中,您可以像任何其他模型属性一样显示翻译的内容:

<h1>{{ $post-&gt;title }}</h1>
<p>{{ $post-&gt;content }}</p>

结论

通过使用 json 列来存储翻译并实现回退机制,您可以简化 laravel 应用程序中多语言内容的管理。这种方法将翻译整合到单个列中,简化了数据处理并使您的代码库更易于维护。无论您是构建博客、电子商务网站还是任何多语言应用程序,此方法都能确保流畅高效的用户体验。

尽情享受!

卓越飞翔博客
上一篇: php负责哪些内容
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏