
本文档旨在解决在使用 TCG\Voyager 管理后台时,关联模型无法正确翻译的问题。主要针对 Laravel 项目中,使用 Voyager 1.4 版本以及 Laravel 8.0 版本,并且已经配置多语言支持的情况下,如何确保关联关系中的可翻译字段能够根据当前应用语言环境进行正确翻译。通过修改 Blade 模板中的调用方式,可以实现关联模型的翻译。
在使用 TCG\Voyager 管理后台时,可能会遇到关联关系中的模型无法正确翻译的问题。即使主模型使用了 TCG\Voyager\Traits\Translatable trait,并且已经正确配置了可翻译字段,关联模型的可翻译字段仍然可能无法根据当前应用语言环境进行翻译。
以下是一个具体的例子:
假设有三个模型:Process、WorkMachine 和 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 模型中的可翻译字段根据当前应用语言环境进行翻译。
注意事项:
总结:
在使用 Voyager 管理后台时,正确处理关联关系的翻译需要特别注意。通过在 Blade 模板中显式调用 translate(app()->getLocale()) 方法,可以确保关联模型中的可翻译字段能够根据当前应用语言环境进行正确翻译,从而提供更好的多语言支持。
以上就是Voyager 中关联关系的翻译问题解决方案的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号