Coola's avatar
Level 1

Polymorphic Many-to-Many relationship 'where' clause on table after pivot

I have a polymorphic many-to-many relationship with posts and videos such that posts or videos are either visible if 'public' or if the user is associated to the post via the peekables pivot table.

posts
    id - integer
    name - string
    visibility - string // e.g. 'private', 'public'

videos
    id - integer
    name - string
    visibility - string // e.g. 'private', 'public'

users
    id - integer
    name - string

peekables
    user_id - integer
    peekable_id - integer
    peekable_type - string // 'App\Videos' or 'App\Posts'

How do I retrieve the all posts which are either having their visibility set to 'public' or which have a specific user_id associated via the peekables table along with pagination of '5' using Eloquent?

0 likes
2 replies
jeffreyvanrossum's avatar
Level 9

I think you can do a orWhereHas for the peekables part and then do a where user_id is equal to the current user's id.

As an example (not tested):

App\Post::where('visibility', 'public')
  ->orWhereHas('peekables', function($query) {
      $query->where('user_id', auth()->id());
  })
  ->paginate(5);
Coola's avatar
Level 1

Thanks. I was over complicating things in comparison to your solution. It works great!

Please or to participate in this conversation.