
本文档旨在解决在使用 TCG\Voyager 管理后台时,关联模型无法正确翻译的问题。主要针对 Laravel 项目中,使用 Voyager 1.4 版本以及 Laravel 8.0 版本,并且已经配置多语言支持的情况下,如何确保关联关系中的可翻译字段能够根据当前应用语言环境进行正确翻译。通过修改 Blade 模板中的调用方式,可以实现关联模型的翻译。
在使用 TCG\Voyager 管理后台时,可能会遇到关联关系中的模型无法正确翻译的问题。即使主模型使用了 TCG\Voyager\Traits\Translatable trait,并且已经正确配置了可翻译字段,关联模型的可翻译字段仍然可能无法根据当前应用语言环境进行翻译。
以下是一个具体的例子:
假设有三个模型:Process、WorkMachine 和 Product。
- Process 模型 belongsToMany WorkMachine 模型。
- Process 模型 hasMany Product 模型。
所有三个模型都使用了 TCG\Voyager\Traits\Translatable trait,并且定义了各自的可翻译字段。
模型定义:
<?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 = App\Models\Process::where('slug', $processSlug)
->with('get_workmachine')
->with('get_products')
->firstOrFail()->translate(app()->getLocale());尽管 Process 模型本身可以正确翻译,但 WorkMachine 和 Product 模型中的可翻译字段仍然显示默认语言的内容。
解决方案:
问题在于,在 Blade 模板中直接访问关联关系时,并没有显式地调用 translate() 方法。需要修改 Blade 模板中的调用方式,以确保关联模型也进行翻译。
错误示例:
@foreach(json_decode($process->get_workmachine) as $workmachine)
...
...
@endforeach正确示例:
@foreach(json_decode($process->get_workmachine->translate(app()->getLocale())) as $workmachine)
...
...
@endforeach通过在访问关联关系时调用 translate(app()-youjiankuohaophpcngetLocale()) 方法,可以确保 WorkMachine 模型中的可翻译字段根据当前应用语言环境进行翻译。
注意事项:
- 确保所有需要翻译的模型都使用了 TCG\Voyager\Traits\Translatable trait。
- 确保在模型的 $translatable 属性中定义了需要翻译的字段。
- 在 Blade 模板中访问关联关系时,务必调用 translate(app()->getLocale()) 方法。
- 如果关联关系返回的是集合(例如 hasMany),则需要遍历集合中的每个模型,并分别调用 translate(app()->getLocale()) 方法。
总结:
在使用 Voyager 管理后台时,正确处理关联关系的翻译需要特别注意。通过在 Blade 模板中显式调用 translate(app()->getLocale()) 方法,可以确保关联模型中的可翻译字段能够根据当前应用语言环境进行正确翻译,从而提供更好的多语言支持。










