I'm trying to write a laravel database migration with foreign relation. during database migration throwing query exception error.
I tired to migrate tables using laravel rules but during migration it showing the unexpected error.
Users Table
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name', 150);
$table->string('email', 150)->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('phone', 150);
$table->unsignedBigInteger('role_id');
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Roles Table
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('role_name',255);
$table->longText('role_description',255);
$table->integer('sort_order');
$table->enum('status',['A','I','D'])->comment('A-active','I-inactive,D-delete');
$table->enum('is_deleted',['Y','N'])->comment('Y-yes,N-no');
$table->timestamps();
$table->bigInteger('created_by');
$table->bigInteger('updated_by')->default(0);
$table->bigInteger('deleted_by')->default(0);
$table->timestamp('deleted_at')->nullable();
});
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table
jt_users
add constraintusers_role_id_foreign
foreign key (role_id
) referencesjt_roles
(id
) on delete cascade)
role_id
in users migration. Also the migration oder should matter... you must ensure the roles migration should run first. – Vikash Pathak