Laravel 拉雷维尔的关系归属
在我的项目中,我想在category和province表中显示名称,而这个表在user表中与之相关 这是我的密码 在控制器中:Laravel 拉雷维尔的关系归属,laravel,Laravel,在我的项目中,我想在category和province表中显示名称,而这个表在user表中与之相关 这是我的密码 在控制器中: $user=user::with('province','category')->where([['id',$id]])->first(); //relation with province model (invert relation) public function province() { return $this->belongsTo
$user=user::with('province','category')->where([['id',$id]])->first();
//relation with province model (invert relation)
public function province()
{
return $this->belongsTo('App\Model\province');
}
//relation with province model (invert relation)
public function category()
{
return $this->belongsTo('App\Model\category');
}
在型号中:
$user=user::with('province','category')->where([['id',$id]])->first();
//relation with province model (invert relation)
public function province()
{
return $this->belongsTo('App\Model\province');
}
//relation with province model (invert relation)
public function category()
{
return $this->belongsTo('App\Model\category');
}
但作为回报,只返回id,而不返回name和其他属性
在输出中显示:
类别识别号:3
省编号:6
错误的
$user=user::with('province','category')->where([['id',$id]])->first()代码>
将外键和本地键放入relatioships
public function province()
{
return $this->belongsTo('App\Model\province','foreign_key','local_key'); // put your FK and LK here
}
public function category()
{
return $this->belongsTo('App\Model\category','foreign_key','local_key'); // put your FK and LK here
}
你可以通过
$user=user::where('id','=',$id)->first();
if(isset($user))
{
if(isset($user->province))
{
//do whatever you want
}
if(isset($user->category))
{
//do whatever you want
}
}
请重试我已编辑它您的where(['id',$id]])为false正确为where('id',$id)