【发布时间】:2015-09-25 08:44:11
【问题描述】:
例如,假设我的用户表有一个引用外部表(如 HEIGHT)的列。如果我使用:
return \Auth::user()->height_id;
在我的控制器中,我获得了 HEIGHT 表中引用的主键的 ID,但是如何检索外部表中引用的行内的数据?
【问题讨论】:
例如,假设我的用户表有一个引用外部表(如 HEIGHT)的列。如果我使用:
return \Auth::user()->height_id;
在我的控制器中,我获得了 HEIGHT 表中引用的主键的 ID,但是如何检索外部表中引用的行内的数据?
【问题讨论】:
你应该试试
return \Auth::user()->height()->YOUR_HEIGHT_TABLE_FIELD;
这应该是你已经建立了User 和Height 模型之间的关系。
Read More..
【讨论】:
每 cmets再次更新
这取决于用户与身高的关系。
我假设它是一个用户只有一个高度。如果是这种情况,您可以像这样设置您的用户和身高模型。
用户
class User extends Model {
/**
* The user's height
* @see App\Height
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function height()
{
// if you break naming conventions you can specify a different key.
// I am unclear because I do not know your db structure.
// from docs:
// return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
return $this->hasOne('App\Height');
}
}
身高
class Height extends Model {
/**
* The height of a user
* @see App\Height
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function user()
{
return $this->hasOne('App\User');
}
}
控制器
public function show($id)
{
$user = User::with('height')->firstOrFail($id);
return view('yourview')->with(compact('user'));
}
查看
{{ $user->height->height }}
{{ $user->height->id }}
无论你做什么,我都会阅读Eloquent: Relationships。应该会有所帮助。
附录
有几种方法可以做到这一点,我可以立即想到。这些都会导致两个查询,我很确定你可以用一个来实现。
public function show($id)
{
$user_id = \Auth::user()->id;
$user = User::with('height')->firstOrFail($user_id);
return view('yourview')->with(compact('user'));
}
或
public function show($id)
{
$user = \Auth::user();
$height = $user->height();
return view('yourview')->with(compact('user'))->with(compact('height'));
}
或
public function show($id)
{
$user = \Auth::user();
$height = Height::find($user->height_id);
return view('yourview')->with(compact('user'))->with(compact('height'));
}
【讨论】:
Illuminate\Database\Eloquent\Relations\HasOne::$height 但是该列在表中称为“高度”...
$this->belongsTo('App\User');?
_id。所以在heights 表中你将拥有user_id,在users 表中你将拥有height_id