S
S
Sergey Zavialov2017-03-30 09:57:57
Laravel
Sergey Zavialov, 2017-03-30 09:57:57

SQLSTATE[42S21] Error Why are foreign keys not being set?

I form a migration to change the table

php artisan make:migration ChangeArticlesTable --table=articles

The migration is successful.
Next, I open the migration file, make entries on the formation of foreign keys
$table->integer('user_id')->unsigned()->default(1);
     $table->foreign('user_id')->references('id')->on('users');         
     $table->integer('category_id')->unsigned()->default(1); 
     $table->foreign('category_id')->references('id')->on('categories');

Next, you need to make changes with the command
php artisan migrate
But the changes are not made, an error message appears:
[Illuminate\DATABASE\QueryException]
SQLSTATE[42S21]: COLUMN already EXISTS: 1060 Duplicate COLUMN name 'user_id' 
(SQL: ALTER TABLE 'articles' ADD 'user_id' INT UNSIGNED NOT NULL DEFAULT1’, ADD 'catego ry_id' INT UNSIGNED NOT NULL DEFAULT ’l’)
[PDOException]
SQLSTATE[42S21]: COLUMN already EXISTS: I960 Duplicate COLUMN name ’user_id'

I don’t understand why foreign keys are not installed, what am I doing wrong? The error points to existing columns, naturally, they exist and I do not intend to change them. The task is to establish foreign keys.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
alexspi, 2017-03-30
@alexspi

uhmm, so what? the religion does not allow to create at once the table with keys?

N
Nimfus, 2017-03-30
@Nimfus

Schema::table('articles', function ($table) {
           $table->foreign('user_id')
                ->references('id')->on('users');

            $table->foreign('category_id')
                ->references('id')->on('categories');
        });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question