2016-04-12 11 views
1

私は少し問題に直面しています、私はユーザとのテーブルアドレス関係の私のデータを取得しようとします。Laravel関係テーブルユーザとアドレス

私のDBアドレスには、ユーザーのテーブルIDに関連付けられた外部キーuser_idがあります。

マイモデルユーザー

public function addresses() 
{ 
    return $this->belongsToMany('Address'); 
} 

マイモデルAddresse

public function user(){ 
    return $this->hasOne('User'); 
} 

私は私のプロフィール方法でユーザー コントローラのユーザーのアドレスを表示しようとする私がUserControllerに取得しよう

public function profile($id){ 
    if($id != Auth::user()->id){ 
     return Redirect::to('logout'); 
    } 
    $user=User::find(Auth::user()->id); 
    $address = $user->addresse; 
    dd($address); 
    $comments = Comment::where('user_id','=',Auth::user()->id) 
     ->take(10)->get(); 

    return View::make('users.profile') 
     ->with(array('comments'=>$comments,'address'=>$address)); 
} 

私の見解では、私のrelatのデータを取得することはできませんイオンユーザーアドレス。あなたのテーブルで

profile.blade.phpビュー

答えて

1

[OK]を、あなたは夫婦のエラーを持っています。まず、Auth :: user()がすでにユーザーモデルであるため、ユーザーを再度定義する必要はありません。だからすべてを行う必要がある $ user = Auth :: user();

し、あなたの目的は、各ユーザーのための単一のアドレスレコードを持っている場合、その

public function profil($id){ 
     ...... 
     $user=Auth::user(); 
     // this will bring users all related addresses as an array. 
     //so you can loop through and use them. 

     $adress = $user->adresses; 

     .......... 
} 

した後、あなたはあなたのモデルにいくつかの変更を行う必要があります。

あなたのユーザーモデルでは、address_id列を追加し、アドレステーブルからuser_id列を削除するだけです。このようにして、あなたは1対1の関係になります。各ユーザーには1つのアドレスしかありません。

その後、ユーザーモデル内のアドレス()関数を削除し、アドレス(単数)機能

public function address(){ 
     return $this->belongsTo("Address"); 
} 

とあなたのアドレスモデルで

public function user(){ 
     return $this->hasOne("User"); 
} 

を追加し、あなたが必要なものを提供します。あなたのコントローラのクラスで

public function profil($id){ 
     ...... 
     $user=Auth::user(); 
     $adress = $user->adress; 
     // will give you a single address record belongs to user. 

     .......... 
} 
+0

thxその作業は素晴らしい – nicolassiuol

+0

クール、私はあなたの問題を解決してうれしいです。正解とマークすることができれば幸いです。ありがとう。 –

0

にアドレスUSER_IDを削除して、テーブルのユーザーに列名ADDRESS_IDを作成します。

変更

モデルユーザー:

public function addresses() 
{ 
return $this>belongsToMany('address_id','Address'); 
} 

この: $アドレス=する$ user->アドレス:このため

$address = $user->Address->address(name of the row with the address);