Laravel 从 Post 获取用户
Laravel Getting User From Post
我有 3 个 table 彼此相关。
用户、客户、注释
用户可以向客户端添加备注。
笔记table有以下
id, user_id, client_id, note
在我的客户页面上 "client/{id}" 我正在打印为特定客户添加的所有注释。
但是,我无法从注释中的用户 table 获取用户名。
当我尝试提取发布该注释的用户的姓名时,它说正在尝试获取 属性 非对象。
客户端控制器
$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()
但这将打印出用户行的整个数组(这是正确的数组)。
我相信 belongsTo
和 hasMany
需要他们引用的模型的完整路径。
所以:
备注
public function user() {
return $this->belongsTo('App\User');
}
用户
public function notes() {
return $this->hasMany('App\Note');
}
使用
找到了问题的修复方法
$note->user()->pluck('name')
不要认为这是最好的方法。虽然,它有效。
尝试:
更改此行
$client = Client::find($cid);
到
$client = Client::find($cid)->load('notes.user');
或
$client = Client::find($cid)->with('notes.user')->get();
我有 3 个 table 彼此相关。
用户、客户、注释
用户可以向客户端添加备注。
笔记table有以下
id, user_id, client_id, note
在我的客户页面上 "client/{id}" 我正在打印为特定客户添加的所有注释。
但是,我无法从注释中的用户 table 获取用户名。
当我尝试提取发布该注释的用户的姓名时,它说正在尝试获取 属性 非对象。
客户端控制器
$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()
但这将打印出用户行的整个数组(这是正确的数组)。
我相信 belongsTo
和 hasMany
需要他们引用的模型的完整路径。
所以:
备注
public function user() {
return $this->belongsTo('App\User');
}
用户
public function notes() {
return $this->hasMany('App\Note');
}
使用
找到了问题的修复方法$note->user()->pluck('name')
不要认为这是最好的方法。虽然,它有效。
尝试: 更改此行
$client = Client::find($cid);
到
$client = Client::find($cid)->load('notes.user');
或
$client = Client::find($cid)->with('notes.user')->get();