2016-05-29 23 views
1

私はユーザ、投稿、およびユーザをまとめて結び付ける友人の関連テーブルを持っています。異なるテーブル間の関連テーブルクエリ

1人のユーザーの場合、そのユーザーと友人であるユーザーに属するすべての投稿を取得する必要があります。

//user model 
function posts() { 
    return $this->hasMany('Post'); 
} 
function friends() { 
    return $this->belongsToMany('User', 'friends', 'friend_id', 'user_id'); 
} 

//post model 
function user() { 
    return $this->belongsTo('User'); 
} 

誰かが正しい方向に私を指すことができれば、それは素晴らしい

答えて

1

少しトリッキーと厄介だろうけどべきのようなhasManyThrough関係定義

$friends = $user->friends()->lists('id'); 
$friendsPosts = Post::whereIn('user_id', $friends); 
1

作品:

function friendsPosts() { 
    return $this->hasManyThrough('Post', 'User', 'post_id', 'user_id'); 
} 
関連する問題