0
votes

I am trying to implement many to many relationship using a pivot table. The name of my pivot table is "post_tag" and column names are "post_id" and "tag_id". The post and tag model classes look like below.

class Post extends Model
{
    protected $fillable = array(
        'title',
        'text',
        'active',
        'user_id'
    );

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

    public function comments()
    {
        return $this->hasMany('App\Comment');
    }

    public function tags()
    {
        return $this->hasMany('App\Post', 'post_id');
    }

}

And the tag class is as below:

class Tag extends Model
{
    public function posts()
    {
        return $this->hasMany('App\Post');
    }
}

The post_tag table looks like below:

post_id tag_id
1        1  
1        2  
2        1  

I am trying the tags for the post using the following code:

$user = User::find(1);
    foreach ($user->posts as $post) {
        foreach ($post->tags as $tag) {
            print $tag->title;
            print "<br>";
        }
        print "<br>";
    }

But it throws an error:

QueryException in Connection.php line 729: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'posts.post_id' in 'where clause' (SQL: select * from posts where posts.post_id = 1 and posts.post_id is not null)

I think I missing something. Could anyone please let me know.

Thanks

1
your tags method on Post model must connect to App/Tag instead of App/Post - follio

1 Answers

1
votes

You are set wrong relationship in tags() method of Post Model. It should be return $this->belongsToMany('App\Tag');

And in posts() method of Tag Model you should set return $this->belongsToMany('App\Post');

For more information you can see it in laravel docs