2017-02-01 2 views
1

사용자 프로필 페이지를 만들고 있는데 사용자 모델 및 UserProfile 모델에서 데이터를 검색하고 싶습니다. 그러나 결과를 얻는데 문제가 있습니다. 여기에 내가했던 일이야 :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'); 
    } 

} 

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); 



    } 

의 관계에 액세스 그리고이있어 잘못하다 나 :

또한
$user = User::with('profile')->where('username', $username)->first(); 

,이 경우에 당신이 사용자 개체를 얻을 수있는 first() 방법을 사용한다 :

Call to undefined relationship [user_profile] on model [App\User]. 

user_profile로

+0

구문이 올바르지 않습니다. 사용자 모델의 사용자 및 사용자 프로필 간의 관계를 씁니다. 그럼 전화 해. –

+0

나는 이미 관계가 있습니다. 잠깐, 내 게시물을 업데이트하십시오. – Jerielle

답변

1

를 사용하여 적절한 관계 이름 내 테이블 이름입니다.

+0

'User'와'UserProfile' 이외에'ProfileController'에도 관계가 필요합니까? – Jerielle

+0

@Jerielle 방금 방금 질문을 적절한 관계 코드로 업데이트 했으므로 지금 내 답변에 설명 된대로 사용해야합니다. –

+0

확인해보십시오. – Jerielle

관련 문제