Laravel关系类别和帖子

时间:2015-01-25 11:33:31

标签: laravel eloquent

添加关系类别和帖子时出现问题。在数据库中有三个表:类别(category_id,标题),帖子(post_id,文本,标题),category_post(category_id,post_id)。 需要添加表category_post,但不能添加。这是模型类别和帖子以及它们之间的关系。

    class Category extends Eloquent{
    protected $table = 'categories';
    protected $primaryKey = 'category_id';

    public function posts()
    {
        return $this->hasMany('Post');
    }
}
class Post extends Eloquent
{
    protected $table = 'post';
    protected $primaryKey = 'post_id';

    public function category()
    {
        return $this->belongsTo('Category');
    }

    //Method add post. Called in the controller
    public static function add($data)
    {
        try {
            $post = new Post;
            $post->title = $data['title'];
            $post->text = $data['text'];

            $category = Category::find(1);
            $category->posts()->save($post);
        }catch (Exception $e){
            return $e;
        }

        return $category;
    }
}

返回例外。请帮帮我。

0 个答案:

没有答案