其中很多答案都是正确的,但我想我会提供一种不同的方法。
1。创建一个新表
考虑创建一个名为 chapters 的附加表。
使用以下命令执行此操作:
php artisan make:model Chapter -m
这将创建一个模型并进行迁移。
迁移将如下所示:
Schema::create('chapters', function (Blueprint $table) {
$table->id();
$table->integer('number')->unsigned();
$table->string('heading');
$table->timestamps();
});
2。将外键添加到旧表中
然后根据您的屏幕截图修改您的模型。从这里开始,我假设和其他人一样,这个表叫做translation,模型叫做Transaltion。
您的新迁移应如下所示:
Schema::create('translations', function (Blueprint $table) {
$table->id();
$table->foreignId('chapters_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
$table->string('translation');
$table->timestamps();
});
3。将关系添加到模型
Translation型号
public function chapters()
{
return $this->belongsTo(Chapter::class);
}
Chapter型号
public function translations()
{
return $this->hasMany(Translation::class);
}
4。使用新关系
您现在可以查询每个标题,而不必使用groupBy 或任何其他方法。
以下是其中一些示例。
4.1 我们有多少章?
Chapter::count();
4.2 第1章有多少个句子?
Chapter::where('number', 1)->translations()->count();
// or if you want to get a Collection of them
Chapter::where('number', 1)->translations;
// or if you just want a certain few columns
Chapter::where('number', 1)->translations()->select('translation', 'sentence')->get();
4.3 如何获取所有章节和对应的翻译?
$chapters = Chapter::with('translations')->get();
然后在你的刀片视图中,执行:
@foreach ($chapters as $chapter)
<h1>{{ $chapter->heading }}</h1>
<p>Sentences:</p>
@foreach ($chapter->translations as $sentence)
<p>{{ $sentence }}</p>
@endforeach
@endforeach