我想在mysql数据库表中添加多个标签,在这种情况下,当尝试添加单个标签然后它没关系但是当尝试插入多个标签时显示这种类型的错误。这是我的迁移和存储代码。
public function store(CreateArticleRequest $request)
{
$article = Auth::user()->articles()->create($request->all());
$article->tags()->attach($request->input('tags'));
flash()->overlay('Your articles has been created!', 'Good Job');
return redirect('articles');
}
以下是迁移代码:
public function up()
{
Schema::create('tags',function(Blueprint $table){
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('articles_tag',function(Blueprint $table) {
$table->increments('articles_id')->unsigned()->index();
$table->foreign('articles_id')->references('id')->on('articles')->onDelete('cascade');
$table->integer('tag_id')->unsigned()->index();
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
$table->timestamps();
});
}
以下是刀片中的表单代码标记选择框:
<div class="form-group">
{!! Form::label('tags','Tags:') !!}
{!! Form::select('tags[]',$tags,null,['class'=>'form- control','multiple']) !!}
答案 0 :(得分:1)
您的迁移错误。表articles_tag
是一个数据透视表,因此您无法对该表中的articles_id
列使用增量。
要解决此问题,请替换此行:
$table->increments('articles_id')->unsigned()->index();
这一个:
$table->integer('articles_id')->unsigned()->index();