[英]How to access other related model data in Laravel?
我創建一個用戶的個人資料頁,我想從我的用戶模型和用戶配置模型檢索數據。 但是我在獲得結果時遇到了問題。 這是我所做的:
用戶模型
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是我的表名
使用正確的關系名稱:
$user = User::with('profile')->where('username', $username)->first();
此外,在這種情況下,您應該使用first()
方法來獲取用戶對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.