我想在 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();
});
}
这是 Blade 中的表单代码标签选择框:
<div class="form-group">
{!! Form::label('tags','Tags:') !!}
{!! Form::select('tags[]',$tags,null,['class'=>'form- control','multiple']) !!}
最佳答案
你的迁移是错误的。 articles_tag
表是一个数据透视表,因此您不能对该表中的 articles_id
列使用增量。
要解决这个问题,请替换这一行:
$table->increments('articles_id')->unsigned()->index();
用这个:
$table->integer('articles_id')->unsigned()->index();
关于php - 违反完整性约束 : 1062 Duplicate entry '25' for key 'PRIMARY' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31740080/