
本文档旨在解决在使用 TCG\Voyager 管理后台时,关联模型无法正确翻译的问题。我们将详细介绍如何在 Laravel 项目中,通过 Voyager 实现关联模型的翻译,并提供具体的代码示例和解决方案,帮助开发者轻松应对多语言环境下的数据展示需求。
问题描述
在使用 Voyager 管理后台进行多语言网站开发时,经常会遇到关联模型无法自动翻译的问题。例如,一个 Process 模型关联了 WorkMachine 和 Product 模型,尽管 Process 模型本身可以正确翻译,但其关联的 WorkMachine 和 Product 模型却无法根据当前应用语言环境进行翻译。
模型配置
首先,确保你的模型已经正确配置了 Translatable trait,并且定义了 $translatable 属性,指定需要翻译的字段。
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use TCG\Voyager\Traits\Translatable;
class Process extends Model
{
use Translatable;
protected $translatable = ['name', 'meta_description', 'description'];
public function get_workmachine() {
return $this->belongsToMany(WorkMachine::class, 'process_workmachine');
}
public function get_products() {
return $this->hasMany(Product::class, 'process_product');
}
}<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use TCG\Voyager\Traits\Translatable;
class WorkMachine extends Model
{
use Translatable;
protected $translatable = ['name', 'meta_description', 'description'];
}<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use TCG\Voyager\Traits\Translatable;
class Product extends Model
{
use Translatable;
protected $translatable = ['name'];
}控制器处理
在控制器中,获取 Process 模型时,需要使用 translate() 方法来获取当前语言环境下的翻译。
$process = App\Models\Process::where('slug', $processSlug)
->with('get_workmachine')
->with('get_products')
->firstOrFail()->translate(app()->getLocale());视图层处理
关键在于视图层如何处理关联模型的翻译。直接在循环中使用 json_decode() 方法并不能触发翻译。
错误示例:
@foreach(json_decode($process->get_workmachine) as $workmachine)
...
...
@endforeach正确示例:
需要在视图层对关联模型进行翻译。 对于 belongsToMany 关系,需要对结果集进行翻译。
@foreach($process->get_workmachine as $workmachine)
{{ $workmachine->translate(app()->getLocale())->name }}
@endforeach或者,如果需要传递整个翻译后的模型,可以这样处理:
@foreach($process->get_workmachine as $workmachine)
@php
$translatedWorkmachine = $workmachine->translate(app()->getLocale());
@endphp
{{ $translatedWorkmachine->name }}
...
@endforeach对于 hasMany 关系,同样需要在循环中进行翻译。
@foreach($process->get_products as $product)
{{ $product->translate(app()->getLocale())->name }}
@endforeach注意事项
- 确保 WorkMachine 和 Product 模型中需要翻译的字段已经存在相应的翻译数据。
- translate(app()-youjiankuohaophpcngetLocale()) 方法返回的是翻译后的模型实例,可以直接访问其属性。
- 如果在控制器中使用 with(['get_workmachine' => function ($query) { $query->withTranslation('de'); }]) 尝试预加载翻译,可能不会生效,因为 Voyager 的翻译机制可能需要显式调用 translate() 方法。
- 确保 app()->getLocale() 返回正确的当前语言环境。
总结
通过在视图层显式调用 translate(app()->getLocale()) 方法,可以解决 Voyager 中关联模型无法自动翻译的问题。这种方法确保了关联模型能够根据当前应用语言环境正确显示翻译后的内容,从而实现完整的多语言支持。记住,需要在每个需要翻译的关联模型实例上都调用 translate() 方法,才能保证翻译的正确性。










