我建立了两个模型,并建立了它们之间的关系。我希望传递用户和user_detail的属性。
我在某个地方使用过类似的代码,它工作得很好。但它在这里是行不通的。
//This is the function in "User.php" model.
public function user_detail(){
return $this->hasOne('App\Profile');
}
//This is the function in "Profile.php" model.
public function user(){
return $this->belongsTo('App\User');
}
//edit function in ProfileController
public function edit($id)
{
$user=User::find($id);
return view('profile.edit')->with('data',$user->user_detail);
}当我在视图中单击编辑按钮时,我希望看到从user表和user_detail表中提取所有详细信息。
发布于 2019-01-23 12:06:24
尝试使用where而不是find,然后使用with
$user = User::where('id', $id)->with('user_detail')->first();
return view('profile.edit')->with('data', $user);在您的模型中
public function user_detail(){
return $this->hasOne('App\Profile', 'student_no');
}发布于 2019-01-23 14:25:36
我认为你应该稍微修改一下你的代码
public function edit($id)
{
$user=User::findOrFail($id);
return view('profile.edit')->with('data',$user);
}在您的刀片文件(profile.edit)中,您可以从用户和配置文件模型中获取所有详细信息。
{{ $data->id }}
{{ $data->user_detail->YOURPARAMETERS }}发布于 2019-01-23 14:55:23
问题出在关系命名上。让它像camelCase一样,
//This is the function in "User.php" model.
public function userDetail(){
return $this->hasOne('App\Profile');
}
//edit function in ProfileController
public function edit($id)
{
$user=User::find($id);
return view('profile.edit')->with('data',$user->userDetail);
}参考:https://github.com/laravel/framework/issues/4307#issuecomment-42037712
https://stackoverflow.com/questions/54319708
复制相似问题