2016-05-18 8 views
0

これらは私のテーブルです:laravelの1つのテーブル内で親子関係を取得する最も良い方法は?

ユーザー

id  username  password 
1  user1   ******** 
2  user2   ******** 
3  user3   ******** 
4  user4   ******** 
5  user5   ******** 
6  user6   ******** 

UserConnections

pivot_id parent_user_id child_user_id 
1   1    2 
2   1    3 
3   3    4 
4   3    5 
class User extends Model 
{ 
    public function connections() 
    { 
     return $this->hasMany('App\UserConnections')->with(['parent','child']); 
    } 
} 

class UserConnection extends Model 
{ 
    public function parent() 
    { 
     $this->belongsTo('App\User','parent_user_id'); 
    } 

    public function child() 
    { 
     $this->belongsTo('App\User','child_user_id'); 
    } 
} 

$user = App\User::find(3); 

今、私は、ユーザーID 3の$user->connectionsを呼び出すとき、

それは

UserConnectionsテーブルから私のexplaination 2,3 & 4行を与えるべきである:第二行で
を、USER3行でUSER1
ある親を有する第&第四、USER3は、二つを有しています子供

+0

。 接続テーブル - id、タイプ(例:{[1 => 'parent'、2 => 'child']}) UserConnectionには誰が誰とどのような接続タイプを持っていますか。 –

+0

@Autista_zあなたのソリューションから、私は1つの接続のために2つの行を作成しなければなりません、親と子供のための1つです。 –

+0

それを考えた後、私はあなたの解決策が最高だと分かった@Autista_z助けてくれてありがとう。 –

答えて

0

これは私の問題を解決するものである:

ユーザー

id  username  password 
1  user1   ******** 
2  user2   ******** 
3  user3   ******** 
4  user4   ******** 
5  user5   ******** 
6  user6   ******** 

UserConnections:@Autista_zへ

pivot_id parent_user_id child_user_id relation 
1   1    2    child 
2   2    1    parent 
3   1    3    child 
4   3    1    parent 
5   3    4    child 
6   4    3    parent 
7   3    5    child 
8   5    3    parent 
class User extends Model 
{ 
    public function connections() 
    { 
     return $this->belongsToMany('App\Newsroom','UserConnections','parent_user_id','child_user_id')->with(['user']); 
    } 
} 

class UserConnection extends Model 
{ 
    public function user() 
    { 
     $this->belongsTo('App\User','child_user_id'); 
    } 
} 

おかげで私はあなたのUserConnectionsテーブルを変更し、接続テーブルを追加する場合、それは、より簡単に、より正確になると思います

+0

私は助けてうれしいです。これは確実な解決策です。今すぐあなたは簡単に両親、子供を取得することができます... あなたの元のソリューションでは少し難しかったです。 –

+0

@Autista_zまさに。再度、感謝します。 –

関連する問題