I'm running into problems with Laravel migrations and creating database tables. Specifically with the constraints.
When I execute the command php artisan:migrate fresh I get the following error:
SQLSTATE[42000]: Syntax error or access violation: 1068 Multiple primary key defined (Connection: mysql, SQL: alter table
usersadd primary key (id))`
So I'm building a website with 3 database tables:
- Users,
- Questions
- Comments
Questions has a column called user_id and should be bound to id in the table Users.
Comments also has a user_id table, and should also be bound to id in Users.
In addition, it also has a question_id column, which should be connected to id in the Question table.
Here are the Laravel migrations:
Users:
Schema::create('users', function (Blueprint $table) {
$table->id()->primary();
$table->text('name');
$table->enum('role', ['admin', 'user'])->default('user');
$table->string('password');
$table->timestamps();
});
Comments:
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('question_id');
$table->text('title');
$table->text('body');
$table->timestamps();
});
Schema::table('comments', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('question_id')->references('id')->on('questions');
});
Questions:
Schema::create('questions', function (Blueprint $table) {
$table->id()->primary();
$table->unsignedBigInteger('user_id');
$table->text('title');
$table->text('name');
$table->text('description');
$table->text('body');
$table->timestamps();
});
Schema::table('questions', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users');
});
This is literally in the Laravel docs, and I don't know what I'm doing wrong. I was hoping someone could give me more insight in what's going wrong and how to fix it. Is it the order in which the migrations are executed?
Thanks in advance :)
I tried making my database tables with Laravel migrations.
I was expecting to create database tables by running the migration files.
I got the following error:
SQLSTATE[42000]: Syntax error or access violation: 1068 Multiple primary key defined (Connection: mysql, SQL: alter table
usersadd primary key (id))
Hey i see you specifically add
primary()with your id() in user migration.Try to remove
primarybecauseid()is by default an alias forbigIncrementsand it creates an auto-incrementingUNSIGNED BIGINT (primary key)equivalent column.For reference you can look in laravel doc