[英]Wrong table when updating "Belongs To" relationships in Laravel
在這里,我正在嘗試使用存在於類別表中的給定 id 保存文章的類別,我已經設置了關系,但是在嘗試保存時,Laravel 嘗試在文章表中而不是數據透視表中插入新行。 這是錯誤:
*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');
}
}
不確定,但在我看來,關系應該是:
articlass Article extends Model implements SluggableInterface
{
public function category()
{
return $this->belongsTo('App\ArticleCategory', 'category_id');
}
}
和
class Category extends Model implements SluggableInterface
{
public function articles()
{
return $this->hasMany('App\ArticleCategory','article_id');
}
}
所以它引用了數據透視表
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.