【发布时间】:2021-03-31 08:02:25
【问题描述】:
我遇到了无法通过数据透视表检索数据的问题,
在我的应用程序中有一个单独的表来存储文件数据,一个单独的表来存储比赛和一个单独的表来存储团队。
还有一个名为competition_file 的表,其中包含competition_id, team_id, file_id。
用户可以通过选择团队或不选择团队来将多个文件添加到比赛中,如下图所示
它将被同步到competition_file表,如下图所示
我需要将 UI 中的所有数据显示为如下图所示的表格
我想知道如何填写使用数据透视表选择的team name
File Model中的关系
public function teams()
{
return $this->belongsToMany(Team::class,'competition_file')->wherePivot('type','document');
}
Competition Model中的关系
public function documents()
{
return $this->belongsToMany(File::class,'competition_file','competition_id', 'file_id')->wherePivot('type','document');
}
这是我的controller index 函数
public function index($id)
{
$competition = $this->competitionsRepo->find($id,[
'team',
'documents',
]);
return view('competitions.document',[
'competition'=>$competition,
]);
}
我的剑
@foreach ($competition->documents as $key=>$document)
<tr>
<td>{{ $key+1 }}</td>
<td>{{ $document->name }}</td>
<td>-</td>
<td>{{ $document->created_at->toDateString() }}</td>
<td>
<form class="confirm" action="{{ route('documents.destroy',['competition'=>$competition,'document'=> $document->id]) }}" method="POST"
data-confirm-title="Remove Document?"
data-confirm-message="Are you sure you want to remove this document?">
@csrf
@method('DELETE')
<button type="submit" name="button" class="button">Remove</button>
</form>
</td>
</tr>
@endforeach
请有人帮我在刀片中获取团队名称到我的 foreach
我希望我的问题很清楚,如果没有问题请评论编辑问题
【问题讨论】:
-
您是否只有上面发布的一个 UI,用于插入有关团队、比赛、文件和比赛文件的数据?我问这个是因为如果你有不同的用户界面,我需要以不同的方式思考你的问题。
-
@RameshKC 不,我有不同的 UI 来创建比赛,只有在创建比赛后,我们才能将球队添加到比赛中,并通过选择球队或不选择球队来将文件添加到比赛中.
-
Jareer, foreach ($competition->documents as $key=>$document) ,这里的比赛有很多文件,所以 $document 会给你一个集合的结果,所以要显示你的团队名称可能需要使用另一个循环。您不能直接使用 $document->teams->name。
-
@RameshKC 我在下面添加了一个答案,无论如何感谢您的时间,这是我的错,我在 Laravel 中不知道
Eager Loading,我必须学习它并且我能够修复问题。
标签: php laravel pivot pivot-table laravel-7