在laravel 5.7中显示数据透视表中的数据

时间:2018-10-22 10:00:05

标签: laravel eloquent pivot-table

如何显示数据透视表中的数据?

我想显示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_projectsuser_idproject_id

form

mockup

1 个答案:

答案 0 :(得分:0)

您误导了基本概念。您已经通过数据透视表在usersprojects之间定义了一个多对多关系,这很好(模型很好)。 但是您的控制器视图代码是错误的。一种方法...

  • ...显示与登录用户具有相同项目的所有用户 ...
  • ...以及他们一起工作的项目名称(通过数据透视表)...
  • ...并且假设您已经在Laravel中正确实现了基本身份验证,可能是:

控制器

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>