数据透视表未按预期工作

时间:2013-05-29 15:08:14

标签: many-to-many laravel laravel-4

我正在尝试使用帖子和类别模型之间的多对多关系。到目前为止,我创建了posts,categories和post_categories表。

在我的模特中,我有自己的关系

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');
    } 
}

当我尝试通过以下方式创建Post实例时,在我的控制器中:

$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'));
    }

提交表单后,我可以看到正常创建的博文。当我检查数据库时,在post_categories表中插入了Category_id,但post_id始终为0.

任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我以错误的方式使用关系。该表必须知道第二个表列名称。

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');
    } 
}

最佳用法是更改表名并将其设为category_post表。这样我所要做的就是

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