4 years ago

Querying using pivots

Posted 4 years ago by berkayk


I am building a simple web app where each Post hasMany Photo and each Photo belongsToMany Tag with photo_tag pivot table. Everything works fine, however, I am not able to get photos in a post with given tag id.

For instance, I am getting photos with = 2, with

$tag = Tag::find($tagId);
$photos = $tag->photos()->groupBy('post_id')->orderBy('post_id','desc')-get();

This gives me all posts which have at least one photo with tag 2. From this point, I would like to query other photos in a given post with the same tags. Below are my models.

Thanks for the help.

Post model:

public function photos(){
        return $this->hasMany('App\Models\Photo', 'post_id');

Photo model:

public function post(){
        return $this->belongsTo('App\Models\Post','post_id');

public function tags(){
        return $this->belongsToMany('App\Models\Tag', 'photo_tag', 'photo_id', 'tag_id');

and finally Tag model

public function photos(){
        return $this->belongsToMany('App\Models\Photo');

Please sign in or create an account to participate in this conversation.