Laravel Blade 如何获取 parent 关系数据

Laravel Blade how to fetch parent relation data

我根据以下关系连接了两个模型。一个 Customer 可以有多个项目,而一个 Project 只能有一个 Customer。假设我的以下模型实现了上述关系。

字段定义

项目

id, description, customer (<= customer 是引用 Project.id 的外键)

客户

id, description


项目模型:

public function customer()
{
  return $this->belongsTo('App\Models\Customer', 'customer', 'id');
}

客户型号:

public function projects()
{
  return $this->hasMany('App\Models\Project');
}

项目控制器:

public function index()
{
  return view('project.index', ['projects' => Project::with('customer')->paginate(10)]);
}

Blade 视图:

@foreach ($projects as $project)
<tr>
  <td><a href="/projects/{{$project->id}}/edit">{{$project->id}}</a></td>
  <td>{{$project->description}}</td>
  <td>{{$project}}</td>
  <td>{{$project->customer->id}}</td>
</tr>
@endforeach

但是 $project->customer->id 给出 Trying to get property of non-object... 错误。

如果我在 foreach 循环中打印其中一个项目,我得到以下数据集。

{
  "id":1,
  "description":"te",
  "state":"Preliminary",
  "customer":{"id":1,"description":"Test Customer","created_at":"2017-10-19 23:29:27","updated_at":"2017-10-19 23:29:27"},
  "created_at":"2017-10-25 19:06:50",
  "updated_at":"2017-10-25 19:06:50"
}

有人可以帮我弄清楚为什么我不能将 Customer.id 引用为 $project->customer->id 吗?

应该使用$project->Customer->id。注意应该是 Customer 而不是 customer.