Laravel项目中多语言版本页面的关联实现方案咨询
Laravel多语言页面关联方案
针对你遇到的同内容多语言页面关联问题,这里提供两种实用的实现方案,都可以在Laravel中轻松落地:
方案一:使用页面分组表(推荐,扩展性更强)
通过新增一个page_groups表来标识同属一组的页面,每个分组对应一个核心内容的多语言版本集合。
1. 创建迁移文件
首先创建分组表:
php artisan make:migration create_page_groups_table
编辑迁移文件:
Schema::create('page_groups', function (Blueprint $table) { $table->id(); $table->timestamps(); });
然后给pages表添加分组外键:
php artisan make:migration add_page_group_id_to_pages_table
编辑迁移文件:
Schema::table('pages', function (Blueprint $table) { $table->unsignedBigInteger('page_group_id')->after('id'); $table->foreign('page_group_id')->references('id')->on('page_groups')->onDelete('cascade'); });
2. 定义模型关联
创建PageGroup模型:
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; class PageGroup extends Model { protected $fillable = []; // 关联该分组下的所有页面 public function pages(): HasMany { return $this->hasMany(Page::class); } }
修改Page模型:
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; class Page extends Model { protected $fillable = ['title', 'content', 'language_id', 'page_group_id']; // 关联所属分组 public function group(): BelongsTo { return $this->belongsTo(PageGroup::class); } // 获取同分组下的其他语言版本 public function translations(): HasMany { return $this->hasMany(Page::class, 'page_group_id') ->where('id', '!=', $this->id); } }
3. 使用示例
// 获取英文版本的"关于我们"页面 $enPage = Page::where('language_id', 1)->where('title', 'About Us')->first(); // 获取该页面的所有其他语言翻译版本 $translations = $enPage->translations; // 获取分组下的所有语言版本(包含当前页面) $allVersions = $enPage->group->pages;
方案二:使用共享Slug(轻量快捷)
如果不需要额外的分组信息,可以给pages表添加slug字段,用同一个slug标识同内容的多语言页面,同时通过slug + language_id保证唯一性。
1. 创建迁移文件
php artisan make:migration add_slug_to_pages_table
编辑迁移文件:
Schema::table('pages', function (Blueprint $table) { $table->string('slug')->after('title'); // 添加联合唯一索引,避免同语言下重复slug $table->unique(['slug', 'language_id']); });
2. 定义模型关联
修改Page模型,添加翻译关联:
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; class Page extends Model { protected $fillable = ['title', 'content', 'language_id', 'slug']; // 通过slug关联同内容的其他语言版本 public function translations(): HasMany { return $this->hasMany(Page::class, 'slug') ->where('language_id', '!=', $this->language_id); } }
3. 使用示例
// 获取德文版本的"关于我们"页面(slug为about-us) $dePage = Page::where('language_id', 2)->where('slug', 'about-us')->first(); // 获取该页面的所有其他语言翻译版本 $translations = $dePage->translations;
方案选择建议
- 若后续可能需要给分组添加额外属性(如分组排序、核心描述),优先选择方案一;
- 若需求简单,仅需关联多语言版本,方案二更轻量快捷。
内容的提问来源于stack exchange,提问作者Nese Şentürk
相关产品推荐
相关产品推荐

