Home > Software engineering >  Error creating table with foreign key Laravel
Error creating table with foreign key Laravel

Time:02-17

This is my first table migration file :

public function up()
{
    Schema::create('produits', function (Blueprint $table) {
        $table->id();
        $table->string('nom',255)->unique();
        $table->string('photo')->default('default.png');
        $table->longText('description');
        $table->float('prix');
        $table->unsignedBigInteger('categorie_id');
       
        $table->foreign('categorie_id')->refrences('id')->on('categories')->onDelete('cascade');
        $table->timestamps();
    });
}

This is my second table migration file :

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->id();
        $table->string('nom',255)->unique();
        $table->timestamps();
    });
}

This is the error i'm getting :

SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'produits' already exists (SQL: create table `produits` (`id` bigint unsigned not null auto_increment primary key, `nom` varchar(255) not null, `photo` varchar(255) not null default 'default.png', `description` longtext not null, `prix` double(8, 2) not null, `categorie_id` bigint unsigned not null, `created_at` timestamp null, `updated_at` timestamp null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')

I tried both : php artisan migrate , php artisan migrate:refresh

CodePudding user response:

You can try to remove the tables from database and before you run the migrations again, make sure categories migration is created first. If you have created produits migration first, it won't work because when migrations are run, the produits table is created first and it will not find the referenced table which does not exist yet. Therefore, the foreign key constraint will not be created.

CodePudding user response:

Almost, you can try php artisan migrate:fresh, this will remove all tables and create new ones.

Does your migration have the drop method?

 public function down()
{
    statement('DROP TABLE categories');
}
  • Related