Laravel 5.6 多对多关系 - 访问视图中的子字段

Laravel 5.6 Many to Many relationship - accessing child fields in view

我在用户和项目之间存在多对多关系。我正在尝试列出用户项目,但无法访问视图中的子字段:

型号

// Project
public function users() {
    return $this->belongsToMany('App\User')->withTimestamps();
}

// User
public function projects() {
    return $this->belongsToMany('App\Project')->withTimestamps();
}

中级 table: project_user

user_id, project_id, timestamps

控制器

$projects = User::with('projects')->where('id', auth()->user()->id)->get();
return view('home')->with('projects', $projects);

查看

  @foreach($projects as $project)
    - {{ $project->name}}
    <br>
  @endforeach

这个returns没有错误也没有结果

如果我尝试 $projects->projects as $project,我会得到 "projects" 此集合不可用。

如果我在控制器中 return $projects 我得到:

[
  {
  "id": 1,
  "first": "User",
  "last": "Name",
  "organization": "Organization",
  "phone": "5555555555",
  "email": "test@example.com",
  "created_at": "2018-03-22 20:16:20",
  "updated_at": "2018-03-22 20:16:20",
  "projects": [
    {
      "id": 10,
      "name": "Project One for User One",
      "description": "Project Description",
      "created_at": "2018-03-22 20:16:20",
      "updated_at": "2018-03-22 20:16:20",
      "pivot": {
        "user_id": 1,
        "project_id": 10,
        "created_at": "2018-03-22 20:16:20",
        "updated_at": "2018-03-22 20:16:20"
      }
    },
    ...

如何访问子字段 namedescription

首先,您不必查询用户,因为它已经通过身份验证。如果你使用类似 Debugbar package 的东西,你会看到它会查询当前会话的用户。

因此,要获取当前经过身份验证的用户,您只需使用:

$user = auth()->user(); // you can als use this in the view if you want.

在控制器中,您的代码:

$projects = User::with('projects')->where('id', auth()->user()->id)- >get();

将执行查询以获取 所有 具有 id = auth()->user()->id 的用户,并且它将 eagerload 这些用户的所有项目(< - 复数 !!!).

因此 $projects 变量包含具有该 ID 的所有用户,它将在后续查询中附加所有项目。因此,它为您提供了一组用户对象,而不是您想要的项目。这是有道理的,因为您正在查询用户 table.

就个人而言,我会在控制器中做这样的事情:

$user = auth()->user();
$projects = $user->projects->get(); // doing this here will allow you to change get() to paginate() if you want.

return ('home')->with(['projects' => $projects]); // < either use compact as in the docs, or an associative array

现在视图 $projects 将包含项目集合,而不是用户,您可以简单地执行以下操作:

@foreach($projects as $project)
  - {{ $project->name}}
  <br>   
@endforeach