I am trying to add a commenting system on my blog application however I get this error when trying to run comment migration which seems to have nothing to do with my current comments
migration file, but a previous post_tag
migration file
[Illuminate\Database\QueryException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'post_tag' already exists (SQL:
create table `post_tag` (
`id` int unsigned not null auto_increment primary key,
`post_id` int unsigned not null,
`tag_id` int unsigned not null
) default character set utf8 collate utf8_unicode_ci)
This is my comments
migration file
<?php
//2017_01_16_101128_create_comments_table.php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCommentsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email');
$table->text('comment');
$table->boolean('approved');
$table->integer('post_id')->unsigned();
$table->timestamps();
});
Schema::table('comments', function($table){
$table->foreign('post_id')->references('id')->on('posts')->
onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropForeign(['post_id']);
Schema::drop('comments');
}
}
and this is my post_tag
migration file
<?php
2016_12_18_230831_create_post_tag_table.php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostTagTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$table->increments('id');
$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts');
$table->integer('tag_id')->unsigned();
$table->foreign('tag_id')->unsigned();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('post_tag');
}
}
How do I get rid of this error or what am I missing here?
In your CreatePostTagTable
migration you may wont to change
$table->integer('tag_id')->unsigned();
$table->foreign('tag_id')->unsigned();
to
$table->integer('tag_id')->unsigned();
$table->foreign('tag_id')->references('id')->on('tag');
There was a duplication.
Then manually remove post_tag
table. It could have be created once again. You may also want to check on your migration
table in your database as there could be a record of. post_tag
table. If so remove it. Then you could run migration safely.
Additionally since you are creating a pivot table
you don't probably gonna need a $table->increments('id');
. It could be depend on your situation. In most cases you don't need it.