
本文档旨在解决在使用 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通过在视图层显式调用 translate(app()->getLocale()) 方法,可以解决 Voyager 中关联模型无法自动翻译的问题。这种方法确保了关联模型能够根据当前应用语言环境正确显示翻译后的内容,从而实现完整的多语言支持。记住,需要在每个需要翻译的关联模型实例上都调用 translate() 方法,才能保证翻译的正确性。
以上就是Voyager 中关联模型的翻译问题及解决方案的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号