Ad

Laravel Posts And Tags: Has Many Through Relationship?

- 1 answer

I'm making a Laravel application.

I have a posts table that stores "blog posts". I also have a tags table to store tags (eg: "Cooking" for cooking posts, "Books" for book posts). Each post can have many tags. I setup my database as such

Posts

  • id
  • text
  • title

Tags

  • id
  • name

PostTags

  • id
  • tag_id
  • post_id

Is this a "HasManyThrough" relationship in Laravel/Eloquent? I tried setting up my model using

public function tags()
{
   return $this->hasManyThrough('App\Tag', 'App\PostTag')
}

However, this isn't working - throwing exceptions telling me the column names don't exist.

Ad

Answer

This was actually a "belongsToMany" relationship - what I was missing was the fact you can specify a pivot table using an argument when declaring the relationship like so:

public function tags()
{
   return $this->belongsToMany('App\Tag', 'post_tags')
}
Ad
source: stackoverflow.com
Ad