Laravel 7 General error: 1215 Cannot add foreign key constraint - laravel

I've been researching this for hours, can't seem to solve it. Here is the error
General error: 1215 Cannot add foreign key constraint (SQL: alter table 'users' add constraint 'users_discord_id_foreign' foreign key ('discord_id') references 'discord_o_auths' ('id'))
Here is my DiscordOAuths Migration:
public function up()
{
Schema::create('discord_o_auths', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->integer('id')->unique();
$table->string('access_token')->unique();
$table->string('refresh_token')->unique();
$table->bigInteger('token_expiration');
$table->timestamps();
});
}
And here is my Users Migration.
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->id();
$table->boolean('admin')->default(false);
$table->integer('color_scheme')->default(0);
$table->rememberToken();
$table->timestamps();
});
Schema::table('users', function($table) {
$table->engine = "InnoDB";
$table->integer('discord_id')->unsigned();
$table->foreign('discord_id')->references('id')->on('discord_o_auths');
});
}
The DiscordOAuths table is created before the Users table as well. What am I doing wrong?

You're trying to assign a foreign key constraint to an integer column, which is not the same as the unsigned columns that Laravel uses for its id's.
In your DiscordOAuths you have to replace $table->integer('id')->unique(); with $table->bigIncrements('id'); or the new method added in Laravel 7 $table->id(); which is an alias of the previous one.
Your discord_id column in the users migration also needs to be an unsigned column. You have to define it using either $table->unsignedBigInteger('discord_id'); or its alias that came with Laravel 7: $table->foreignId('discord_id');
So your migrations would look like this:
For DiscordOAuths
public function up()
{
Schema::create('discord_o_auths', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->id();
$table->string('access_token')->unique();
$table->string('refresh_token')->unique();
$table->bigInteger('token_expiration');
$table->timestamps();
});
}
And for users it would be like this:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->id();
$table->boolean('admin')->default(false);
$table->integer('color_scheme')->default(0);
$table->rememberToken();
$table->timestamps();
});
Schema::table('users', function($table) {
$table->engine = "InnoDB";
$table->foreignId('discord_id');
$table->foreign('discord_id')->references('id')->on('discord_o_auths');
});
}

Related

Can't make migration to Laravel SQLSTATE[42703]

I keep getting an error when trying to do a database migration
SQLSTATE[42703]: Undefined column: 7 ERROR: column "user_id" referenced in foreign key constraint does not exist (SQL: alter table "ads" add constraint "ads_user_id_foreign" foreign key ("user_id") references "users" ("id"))
This is my migration file
public function up()
{
Schema::create('ads', function (Blueprint $table) {
$table->id();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('category_id')->references('id')->on('categories');
$table->foreign('city_id')->references('id')->on('cities');
$table->string('title');
$table->text('description');
$table->text('photos');
$table->string('status');
$table->timestamps();
});
}
You need first to create the columns before add foreign key
public function up()
{
Schema::create('ads', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('city_id');
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('category_id')->references('id')->on('categories');
$table->foreign('city_id')->references('id')->on('cities');
$table->string('title');
$table->text('description');
$table->text('photos');
$table->string('status');
$table->timestamps();
});
}

laravel migration "SQL: alter table `posts` add constraint `posts_category_id_foreign` foreign key (`category_id`) references `categories` (`id`) "

am trying to do laravel migration but am getting this error
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table `urbancruise`.`#sql-18f8_112` (errno: 150 "Foreign key cons
traint is incorrectly formed") (SQL: alter table `posts` add constraint `posts_category_id_foreign` foreign key (`c
ategory_id`) references `categories` (`id`))
here is my code
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
public function down(){
Schema::drop('categories');
}
public function up(){
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->bigInteger('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
$table->timestamps();
});
}
public function down(){
Schema::drop('posts');
}
When you are creating a foreign key, the categories.id and posts.category_id must have the same type.
Swap the ->bigInteger() with ->integer()should solve your problem:
Your categories migration:
public function up(){
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
public function down(){
Schema::drop('categories');
}
In your posts migration:
public function up(){
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id', false, true);
//Or $table->unsignedInteger('category_id');
$table->foreign('category_id')
->references('id')
->on('categories');
$table->timestamps();
});
}
public function down(){
Schema::drop('posts');
}
Hope it helps.
Foreign key should always be of same type in both child and parent table.
In your case, categories.id is of type ٰINTEGER while posts.category_id is defined as BIGINT. Replacing your posts migration with below should work.
public function up() {
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
$table->timestamps();
});
}

Laravel Foreign key constraint is incorrectly formed after adding $table->engine = 'MyISAM';

After adding $table->engine = 'MyISAM'; seem foreign key is not working anymore. This my main table
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->engine = 'MyISAM';
$table->integer('id');
$table->string('user_id',20);
$table->string('name');
$table->primary(['user_id','id']);
$table->rememberToken();
$table->timestamps();
});
DB::statement('ALTER TABLE users CHANGE id id INT(11) NOT NULL
AUTO_INCREMENT');
}
Foreign key table
public function up()
{
Schema::create('useraccesses', function (Blueprint $table) {
$table->increments('id');
$table->string('user_id',20);
$table->datetime('accessTime')->nullable();
$table->datetime('quittime')->nullable();
$table->datetime('activeHour')->nullable();
$table->text('token')->nullable();
$table->foreign('user_id')
->references('user_id')->on('users')
->onDelete('cascade');
$table->timestamps();
});
}
Thanks
Foreign keys are not supported for MyISAM tables in MySQL. Use InnoDB tables instead. c.f. https://dev.mysql.com/doc/refman/8.0/en/myisam-storage-engine.html
Try this
for users migration
...
$table->increments('id');
...
for useraccesses migration
...
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')
->references('user_id')->on('users')
->onDelete('cascade');
...

Creating Foreign key with string data type in laravel

I have two tables. One is students_attendances and another is students. Now i want to set a foreign key between these two tables. And also I have string data type on which I wanna set foreign key but its giving me the error. Below is my code. Take a review of it ...
//students_attendances Table
public function up()
{
Schema::create('students_attendances', function (Blueprint $table) {
$table->increments('id');
$table->integer('class_id')->index()->unsigned()->nullable();
$table->string('student_id');
$table->string('first_name');
$table->string('last_name');
$table->string('attendance');
$table->timestamps();
$table->foreign('student_id')->references('student_id')->on('students')->onDelete('cascade');
});
}
//students table
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->increments('id');
$table->string('student_id');
$table->string('first_name');
$table->string('last_name');
$table->string('DOB');
$table->integer('students_class_id')->index()->unsigned()->nullable();
$table->string('gender');
$table->string('blood_group');
$table->string('religion');
$table->string('photo_id');
$table->string('student_address');
$table->integer('student_phone_no');
$table->string('guardian_name');
$table->string('guardian_gender');
$table->string('guardian_relation');
$table->string('guardian_occupation');
$table->integer('guardian_phone_no');
$table->string('email')->unique();
$table->string('NIC_no');
$table->string('guardian_address');
// $table->string('document_id');
$table->string('username');
$table->string('password');
$table->timestamps();
});
}
In your students table Change
$table->string('student_id');
to
$table->string('student_id')->unique();
To be used as foreign key, it must be a unique key.
So, the new migration will be
Schema::table('students', function (Blueprint $table) {
$table->unique("student_id");
});

Laravel relationship error in migration

I am trying to make two tables relationship in laravel. But i can't understand why i'm getting error "errno: 150 "Foreign key constraint is incorrectly formed"". please check my migration code below.
items table
public function up()
{
Schema::create('items', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->string('name');
$table->decimal('price',5,2);
$table->integer('count_left')->default(0);
$table->timestamps();
$table->foreign('category_id')->references('id')->on('categories');
});
}
categories
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
});
}

Resources