0
votes

I am trying to use many-to-many relationships between my posts and categories models. So far I created posts , categories and post_categories tables.

In my models, I have my relationships

class Post extends Eloquent {
    public function categories()
    {
        return $this->belongsToMany('Category', 'post_categories','category_id');
    }
}
class Category extends Eloquent {
    public function posts()
    {
        return $this->belongsToMany('Post','post_categories');
    } 
}

and in my controllers when I try to create a Post instance by :

$post = new Post;

        $post->title            = e(Input::get('title'));
        $post->slug             = e(Str::slug(Input::get('title')));
        $post->content          = e(Input::get('content'));
        // Was the blog post created?
        if($post->save())
        {
            $id = (int) Input::get('category_id');
            $category = Category::find($id);

            $post->categories()->attach($category);
            // Redirect to the new blog post page
            return Redirect::to("admin/blogs/$post->id/edit")->with('success', Lang::get('admin/blogs/message.create.success'));
    }

After submitting form , I can see blog post is created normally. When I check the db , Category_id is inserted inside post_categories table but post_id is always 0.

Can anyone help me to fix this?

2

2 Answers

0
votes
$post->categories()->attach($category->id);
0
votes

I was using relationships in a wrong way. The table had to know the second table column name.

class Post extends Eloquent {
    public function categories()
    {
        return $this->belongsToMany('Category', 'post_categories','category_id','post_id');
    }
}
class Category extends Eloquent {
    public function posts()
    {
        return $this->belongsToMany('Post','post_categories',,'post_id','category_id');
    } 
}

The best usage will be changing the table name and make it category_post table. This way all I have to do is

class Post extends Eloquent {
    public function categories()
    {
        return $this->belongsToMany('Category');
    }
}
class Category extends Eloquent {
    public function posts()
    {
        return $this->belongsToMany('Post');
    } 
}