Laravel 5.6多对多关系 - 访问子视野

时间:2018-03-26 20:55:43

标签: laravel-5.6

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

模型

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

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

中级表: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

这不会返回错误,也不会返回结果

如果我尝试$projects->projects as $project,我会收到此系列无法使用的“项目”。

如果我在控制器中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

1 个答案:

答案 0 :(得分:1)

首先,您不必查询用户,因为它已经过身份验证。如果您使用类似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 这些用户的所有项目(&lt; - 复数!!!)。

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

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

$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