2017-12-19 13 views
2

関連するモデルに問題があります。Laravelの複数のリレーションシップ(ピボット)

3つのモデルがあります。ユーザー、ポストタイプ(音楽、動物)、投稿。

ユーザは、見たいポストタイプを選択することができます。だから、私はピボットテーブルposttype_userを作成しました。 これで、ユーザーにバインドされた選択したpostTypesを保存できます。

// User model 
    public function postTypes() 
    { 
     return $this->belongsToMany(PostType::class); 
    } 

// PostType model 
    public function users() 
    { 
     return $this->belongsToMany(User::class); 
    } 

ポストモデルには、postType_idの外部キーがあります。そして、モデルでこの関係:

// Post model 
    public function postType() 
    { 
     return $this->belongsTo(PostType::class); 
    } 

// PostType model 
    public function post() 
    { 
     return $this->hasMany(Post::class); 
    } 

は、今私は、現在のユーザー(認証::ユーザー())から(選択posTypesの)すべての記事を受信したいです。

しかし、私はどのようにわかりません。誰にもアイデアはありますか?

+0

をあなたはhttps://laravel.com/docs/5.5/eloquent-relationships#を読んでから開始する必要があります照会関係 –

答えて

1

あなたは、ネストされたwhereHas()を使用することができます。

Post::whereHas('postType', function($q) { 
     $q->whereHas('users', function($q) { 
      $q->where('id', auth()->id()); 
     }); 
    })->get(); 

それともあなたがこれを行うことができます:

$postTypeIds = auth()->user()->postTypes()->pluck('id'); 
$posts = Post::whereIn('post_type_id', $postTypeIds)->get(); 
関連する問題