在这里,我尝试使用存在于类别表中的给定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();
}
答案 0 :(得分:1)
您的关系类型是多对多的关系,而不是一对多。
你的模特应该是这样的:
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();
});
如果你想要一对多关系不需要' article_category'表格您的迁移应该是这样的:
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');
}
}
和模特:
Private Function foo(ByVal text As String)
Return text
End Function
Private Function foo2(ByVal text As String) As String
Return text
End Function
答案 1 :(得分:0)
不确定,但我认为关系应该是:
class Category extends Model implements SluggableInterface
{
public function articles()
{
return $this->hasMany('App\ArticleCategory','article_id');
}
}
和
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');
}
}
所以它引用了数据透视表