如何显示数据透视表中的数据?
我想显示user
所属的project
和登录的user
以及正在工作的project
以及他们各自的角色。
我使用->groupBy()
吗?
查看:index.blade.php
<table class="table table-consended">
<tr>
<th> <h4>No</h4> </th>
<th> <h4>Name</h4> </th>
<th> <h4>Role</h4> </th>
<th> <h4>Project</h4> </th>
</tr>
@foreach($users as $item => $user)
<tr>
<td>{{$item+1}}</td>
<td>{{$user->name}}</td>
<td>{{$user->role->name}}</td>
<td>{{$user->projects->project_name}}</td>
</tr>
@endforeach()
</table>
我的controller.php
public function index()
{
$users = User::all();
$projects = User::pluck('name')->where('project_id', 3);
$projects = Project::all();
return view ('teams.index', compact ('user_projects', 'users', 'projects'));
}
模型User.php
<?php
class User extends Model
{
protected $fillable = [
'name', 'email', 'password', 'role_id',
];
public function role()
{
return $this->belongsTo(Role::class, 'role_id');
}
public function projects()
{
return $this->belongsToMany(Project::Class, 'user_projects');
}
}
模型Project.php
<?php
class Project extends Model
{
use SoftDeletes;
protected $table = 'projects';
protected $fillable = [
'project_id',
'project_name',
'start_date',
'end_date',
'project_category',
];
public function users() {
return $this->belongsToMany(User::class, 'user_projects');
}
}
我有数据透视表user_projects
有user_id
和project_id
答案 0 :(得分:0)
您误导了基本概念。您已经通过数据透视表在users
和projects
之间定义了一个多对多关系,这很好(模型很好)。
但是您的控制器和视图代码是错误的。一种方法...
控制器
public function index()
{
$user = Auth::user(); // logged in user
$coworkers = []; // coworkers array
$projects = []; // projects array
foreach ($user->projects as $project) {
foreach($project->users as $coworker) {
$coworkers[] = $coworker;
$projects[] = $project;
}
}
return view ('teams.index', ['coworkers' => $coworkers, 'projects' => $projects]);
}
index.blade.php
<table class="table table-consended">
<tr>
<th> <h4>No</h4> </th>
<th> <h4>Name</h4> </th>
<th> <h4>Role</h4> </th>
<th> <h4>Project</h4> </th>
</tr>
@foreach($coworkers as $coworker)
<tr>
<td>{{$loop->iteration}}</td>
<td>{{$coworker->name}}</td>
<td>{{$coworker->role->name}}</td>
<td>{{$projects[$loop->index]->name}}</td>
</tr>
@endforeach
</table>