【发布时间】:2017-02-01 06:02:10
【问题描述】:
我正在创建一个用户个人资料页面,我想从我的 User 模型和 UserProfile 模型中检索数据。但是我在获得结果时遇到了问题。这是我所做的:
用户模型
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'username',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/*
public function isAdmin() {
return $this->admin;
}
*/
public function profile() {
return $this->hasOne('App\UserProfile');
}
}
用户档案模型
class UserProfile extends Model
{
protected $table = 'user_profile';
protected $fillable = [
'phone',
'address'
];
public function user() {
return $this->belongsTo('App\User');
}
}
然后我访问我的 ProfileController 中的关系
public function getProfile($username) {
$user = User::with('user_profile')->where('username', $username)->get();
dd($user);
}
我得到了这个错误:
Call to undefined relationship [user_profile] on model [App\User].
user_profile 是我的表名
【问题讨论】:
-
您的语法不正确。在用户模型中写入用户和用户配置文件之间的关系。然后调用。
-
我已经有关系了。等会更新我的帖子。