2017-12-19 2 views
2

관련 모델에 문제가 있습니다.Laravel의 다중 관계 (피벗)

세 가지 모델이 있습니다. 사용자, 우편 유형 (음악, 동물) 및 우편.

사용자는보고 싶은 포스트 유형을 선택할 수 있습니다. 그래서 피벗 테이블 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();