我有一个名为用户和个人资料的两个表。在个人资料表格中有一个名为userID的列。现在我希望此userID
列从用户表的id
获取值。我已经完成了数据库关系部分。但是无法通过视图检索数据。我已经搜索过,但根据我的问题我没有找到任何令人满意的答案。
顺便说一句,我是Laravel的新手。到目前为止我已经尝试了
用户模型:
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $table ="users";
protected $fillable = [
'userName', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function userProfile(){
return $this->hasOne('App\Profile');
}
}
个人资料模型:
class Profile extends Model
{
//
protected $table = "profiles";
public $fillable = ["firstName","lastName","middleName","DOB","gender","featuredProfile","email","phone","summary","profilePic"];
public function user(){
return $this->belongsTo('App\User');
}
}
我正在尝试使用userID
检索{{$profile->userID}}
。我真的不知道问题出在哪里以及如何做到这一点?
答案 0 :(得分:2)
你需要告诉laravel获得像这样的关系模型
$profile = Profile::find(1);
$userID = $profile->user->id;
编辑: 来自docs
自动假设模型具有user_id外键。
在您的情况下为userId
,因此请更改hasOne
和belongsTo
方法,告诉laravel您正在使用的foreign_key
的名称
public function profile()
{
return $this->hasOne('App\Profile', 'userId');
}
public function user()
{
return $this->belongsTo('App\User', 'userId');
}
答案 1 :(得分:0)
请将userID添加到可填写的个人资料数组中。
请检查以下示例代码以执行相同的操作。
public $fillable = ["firstName","lastName","middleName","DOB","gender","featuredProfile","email","phone","summary","profilePic","userID"];