【发布时间】:2016-12-30 10:55:18
【问题描述】:
我有 3 个相互关联的表。
用户、客户、备注
用户可以向客户端添加注释。
notes 表有以下内容
id, user_id, client_id, note
在我的客户页面“client/{id}”上,我正在打印为特定客户添加的所有注释。
但是,我无法从注释中的用户表中获取用户的名称。
当我尝试提取发布该注释的用户的名称时,它显示尝试获取非对象的属性。
客户端控制器
$client = Client::find($cid);
if (empty($client)) {
return Redirect::to('contact'); //redirect to contacts if contact not found
} else {
$this->layout->content = View::make('clients.show')->with('client', $client);
}
客户端视图
@foreach ($client->notes as $note)
{{ $note->note }} //This works just fine.
Posted by: {{ $note->user->name }}
@endforeach
我的笔记模型:
public function user() {
return $this->belongsTo('User','user_id');
}
我的用户模型:
public function notes() {
return $this->hasMany('Note','user_id');
}
如果我尝试使用该功能,我可以做类似的事情
$note->user()->get()
但这会打印出用户行的整个数组(它是正确的数组)。
【问题讨论】:
标签: php laravel laravel-4 eloquent relationships