Search code examples
phplaravelmany-to-manyrelationship

Many to Many relationship with Laravel


I have the following tables:

Posts {id, title, description}

Tags {id, name, description}

post_tags {post_id, tag_id}

In Laravel I have set up the relations like below. I'm not sure how to query my post_tags pivot table. I get an error of:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dev_match.post_tag' doesn't exist (SQL: select `tags`.*, `post_tag`.`post_id` as `pivot_post_id`, `post_tag`.`tag_id` as `pivot_tag_id` from `tags` inner join `post_tag` on `tags`.`id` = `post_tag`.`tag_id` where `post_tag`.`post_id` = 1)

Home Controller:

  public function getindex(){


          $post = Post::all();
         return view('welcome', compact('post'));

       }

home view:

@foreach($post as $posts)

    <tbody>
        <tr>
        <td> <a href="">{{$posts->tags->name}}</a> </td>
        <td>  </td>
        <td> asked </td>
      </tr>
    </tbody>


    @endforeach

Tag Model:

  public function post()
{
   return $this->belongsToMany('App\Post');
}

Post Model:

    public function tag()
 {
     return $this->belongsToMany('App\Tag');
 }

Solution

  • You don't need to add a model for a pivot table (but you can) and also, you don't need to add an id to a pivot table.

    Your relations are the ok, but if you want to use id, you should add withPivot('id') to the relationships

    public function post()
    {
        return $this->belongsToMany('App\Post')->withPivot('id');
    }