php - 在 Laravel 中更新 "Belongs To"关系时出现错误表

标签 php mysql laravel pivot-table laravel-5.1

在这里,我试图用类别表中存在的给定 id 保存文章的类别,我已经设置了关系但是在尝试保存时,Laravel 尝试在 articles 表 中插入新行而不是数据透视表。 这是错误:

  *Unknown column 'category_id' in 'field list' (SQL: update `articles` set    `category_id` = 1, `updated_at` = 2015-11-16 13:15:32 where `id` = 53)* 

这些是关系和数据透视表

class Article extends Model implements SluggableInterface
{ 
   public function category()
   {
     return $this->belongsTo('App\Category');
   }
}

class Category extends Model implements SluggableInterface
{
     public function articles()
     {
       return $this->hasMany('App\Article','article_category');
     }
}

      //pivot table
    Schema::create('article_category',function(Blueprint $table){
        $table->integer('article_id')->unsigned()->index();
        $table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');

        $table->integer('category_id')->unsigned()->index();
        $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');

        $table->timestamps();
    });

这是我的保存功能

public function store(ArticleRequest $request)
{
    $article=Auth::user()->articles()->create($request ->all());
    $category =Category::find($request ->input('category'));
    $article->category()->associate($category)->save();
}

最佳答案

您的关系类型是多对多关系,而不是一对多。

你的模型应该是这样的:

class Article extends Model implements SluggableInterface
{ 
   public function categories()
   {
     return $this->belongsToMany('App\Category', 'article_category');
   }
}

class Category extends Model implements SluggableInterface
{
     public function articles()
     {
       return $this->belongsToMany('App\Article', 'article_category');
     }
}

如果您想要一对多关系而不需要“article_category”表,您的迁移应该像这样:

Schema::create('articles',function(Blueprint $table){
    $table->integer('id')->increments();
    $table->string('title');
    $table->text('content');

    $table->integer('category_id')->unsigned()->index();
    $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');

    $table->timestamps();
});

和模型:

class Article extends Model implements SluggableInterface
{ 
   public function category()
   {
     return $this->belongsTo('App\Category');
   }
}

class Category extends Model implements SluggableInterface
{
     public function articles()
     {
       return $this->hasMany('App\Article');
     }
}

关于php - 在 Laravel 中更新 "Belongs To"关系时出现错误表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33732422/

相关文章:

mysql - Laravel 中执行了哪些数据库触发器

php - 如何在codeigniter中获取数据库列的总和?

mysql - 为什么 mysql sum 在 mysql 查看表中不起作用?

javascript - 如何使用 laravel 将值数组插入数据库?

mysql:表中未在另一个表中引用的行的列表

mysql - 如何使用 phpmyadmin 检查电子邮件是否存在于两个表中

javascript - 数据表搜索 td 属性

php - 扩展 CWebUser 并重写 Yii accessControl

php - 我编辑的 index.php(主页)不会更新我在 mysql 上的主表

javascript - 如何将 jquery ui 自动完成小部件与数据库连接?