Laravel Blade如何获取父关系数据

时间:2017-10-28 20:08:40

标签: one-to-many laravel-blade laravel-5.5

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

字段定义

项目

iddescriptioncustomer(< = customer是引用Project.id的外键

客户

iddescription

项目模型:

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

客户模式:

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

ProjectController:

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循环中打印一个Projects,我会得到数据集。

{
  "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的原因吗?

1 个答案:

答案 0 :(得分:1)

应该使用$project->Customer->id。请注意,它应该是 C ustomer 而不是客户