why am i getting Cannot add foreign key constraint error when migrating tables? - laravel-migrations

Im trying to migrate my tags tables but i keep getting this error:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table post_tag add constraint post_tag_post_id_foreign foreign key (post_id) references posts (id))
when running:
php artisan migrate:fresh
here is my code:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostTagTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('post_id')->unsigned();
$table->integer('tag_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts');
$table->foreign('tag_id')->references('id')->on('tags');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('post_tag');
}
}
CreateTagsTable:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTagsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('tags');
}
}
How do i fix it?

Related

Laravel migration works on Linux but not on windows

When I try to run my Laravel migration on windows
this is the migration file that fails on Windows but works on Linux.
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTenantOwnerBridgeTable extends Migration
{
/**
* Schema table name to migrate
* #var string
*/
public $tableName = 'tenant_owner_bridge';
/**
* Run the migrations.
* #table tenant_owner_bridge
*
* #return void
*/
public function up()
{
Schema::create($this->tableName, function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->unsignedInteger('tenant_owner_id');
$table->string('tenant_id', 191);
$table->unsignedBigInteger('primary_admin_id');
$table->index(["primary_admin_id"], 'fk_tenant_owner_bridge_user_id_idx');
$table->index(["tenant_id"], 'fk_tenant_owner_bridge_tenant_id_idx');
$table->index(["tenant_owner_id"], 'fk_tenant_owner_bridge_tenant_owner_id_idx');
$table->nullableTimestamps();
$table->foreign('tenant_id', 'fk_tenant_owner_bridge_tenant_id_idx')
->references('id')->on('tenants')
->onDelete('no action')
->onUpdate('no action');
$table->foreign('tenant_owner_id', 'fk_tenant_owner_bridge_tenant_owner_id_idx')
->references('id')->on('tenant_owners_info')
->onDelete('no action')
->onUpdate('no action');
$table->foreign('primary_admin_id', 'fk_tenant_owner_bridge_user_id_idx')
->references('id')->on('users')
->onDelete('no action')
->onUpdate('no action');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists($this->tableName);
}
}
This is the error that is thrown.
SQLSTATE[HY000]: General error: 1005 Can't create table primehybrid.tenant_owner_bridge (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table tenant_owner_bridge add constraint fk_tenant_owner_bridge_tenant_id_idx foreign key (tenant_id) references tenants (id) on delete no action on update no action)
Here is the table that the foreign key references.
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTenantsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up(): void
{
Schema::create('tenants', function (Blueprint $table) {
$table->string('id')->primary();
// your custom columns may go here
$table->timestamps();
$table->json('data')->nullable();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down(): void
{
Schema::dropIfExists('tenants');
}
}
Can someone explain why it works on Linux but not Windows and why it fails on Windows.
Also see my list of migration files:
2012_08_06_000003_create_account_statuses_table.php
2013_08_06_000004_create_countries_table.php
**2014_10_12_000000_create_users_table.php**
2014_10_12_100000_create_password_resets_table.php
2016_06_01_000001_create_oauth_auth_codes_table.php
2016_06_01_000002_create_oauth_access_tokens_table.php
2016_06_01_000003_create_oauth_refresh_tokens_table.php
2016_06_01_000004_create_oauth_clients_table.php
2016_06_01_000005_create_oauth_personal_access_clients_table.php
2018_08_08_100000_create_telescope_entries_table.php
2019_08_19_000000_create_failed_jobs_table.php
**2019_09_15_000010_create_tenants_table.php**
2019_09_15_000020_create_domains_table.php
2020_04_06_222004_create_sessions_table.php
2020_05_15_000010_create_tenant_user_impersonation_tokens_table.php
2020_08_10_170933_create_jobs_table.php
2021_04_30_174805_create_cache_table.php
**2021_08_06_000000_create_tenant_owners_info_table.php**
2021_08_06_000001_create_secret_questions_table.php
2021_08_06_000006_create_recovery_info_table.php
**2021_08_06_000007_create_tenant_owner_bridge_table.php**
2021_08_06_223928_create_permission_tables.php
I don't know why you are adding the index() method, you can simple create a foreign reference by writing something like
For Laravel > 5.5
$table->unsignedBigInteger('primary_admin_id');
$table->foreign('primary_admin_id')
->references('id')
->on('users')
->onUpdate('no action')
->onDelete('no action');
For Laravel 8
$table->foreignId('primary_admin_id')->
->references('id')
->on('users')
->onUpdate('no action');
->onDelete('no action');
Also, you need to keep in mind that your migration should be made in proper order, for example if you have an item_order table, you should have all the required tables which will have references in the item_order table

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row error

Im currently reffering a ecommerce lesson using laravel 8.when creating categories for the products im keep getting this error message while migrating.
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (SQL: drop table if exists products)
This is my create_products_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('name');
$table->string('slug');
$table->text('description');
$table->integer('price');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
and here is create_category_product_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCategoryProductTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('category_product', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->unsigned()->nullable();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->integer('category_id')->unsigned()->nullable();
$table->foreign('category_id')->references('id')->on('category')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('category_product');
}
}
Much appreciate if someone can teach me to solve this. Thank You!

Laravel migration can't create relationship

I have 2 tables, users and friend_requests, and I want to create foreign key, but getting following error.
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table larasocial.#sql-1710_1f5 (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table friend_requests add constraint friend_requests_sender_id_foreign foreign key (sender_id) references users (id) on delete cascade on update cascade)
users migration file
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string("name", 255);
$table->string("surname", 255);
$table->string("email", 255);
$table->string("password", 255);
$table->date("birthday");
$table->string("gender", 255);
$table->string("photo", 255);
$table->integer("recover_code")->default(0);
$table->boolean("confirmed")->default(false);
$table->dateTime("last_visit");
$table->date("created_at");
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
friend_requests migration file
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFriendRequestsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('friend_requests', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer("sender_id");
$table->integer("accepter_id");
$table->foreign("sender_id")->references("id")->on("users")->onDelete("cascade")->onUpdate("cascade");
$table->foreign("accepter_id")->references("id")->on("users")->onDelete("cascade")->onUpdate("cascade");
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('friend_requests');
}
}
I have already tried methods of other similar problems, but they are not solving my problem.
The foreign key column need to be the same data type as the reference it's pointing to. Since your user id is big integer, your reference fields must also be big integers.
Edit for future viewers:
change both columns to unsignedBigInteger

Error: Foreign key constraint is incorrectly formed

I've foreign key error in my HOOFDVRAAGS database but the strange this is that's the exact same as in VRAAGS
SQLSTATE[HY000]: General error: 1005 Can't create table
zonetoets.#sql-1 e8_2f9 (errno: 150 "Foreign key constraint is
incorrectly formed") (SQL: a lter table hoofdvraags add constraint
hoofdvraags_toets_id_foreign fore ign key (toets_id) references
toets (id) on delete cascade) In Connection.php line 458:
SQLSTATE[HY000]: General error: 1005 Can't create table
zonetoets.#sql-1 e8_2f9 (errno: 150 "Foreign key constraint is
incorrectly formed")
Hereby my db-migrations and hopefully someone can help me.
Hereby the relationships
TOETS 1---->N HOOFDVRAAGS 1 ----> N VRAAGS
HOOFDVRAAGS
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateHoofdvraagsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('hoofdvraags', function (Blueprint $table) {
$table->increments('id');
$table->integer('toets_id')->unsigned();
$table->string('titel');
$table->string('tekst');
$table->string('bestandsnaam');
$table->integer('volgnummerHoofdvraag')->default(99);
$table->timestamps();
$table->foreign('toets_id')
-> references('id')
-> on('toets')
-> onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('hoofdvraags');
}
}
TOETS
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateToetsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('toets', function (Blueprint $table) {
$table->increments('id');
$table->string('toetscode');
$table->string('jaargang');
$table->string('vak')->default('wiskunde');
$table->string('hoofdstuk');
$table->string('hoofdstuktitel');
$table->string('maker');
$table->string('datumgemaakt');
$table->integer('volgnummerToets')->default(1);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('toets');
}
}
VRAAG
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSubvraagsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('subvraags', function (Blueprint $table) {
$table->increments('id');
$table->integer('hoofdvraag_id')->unsigned();
$table->string('vraag');
$table->string('antwoord');
$table->integer('punten');
$table->string('bestandsnaam');
$table->integer('volgnummerSubvraag')->default(1);
$table->timestamps();
$table->foreign('hoofdvraag_id')
-> references('id')
-> on('hoofdvraags')
-> onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('subvraags');
}
}
MODEL TOETS
public function hoofdvraag()
{
return $this->hasMany(Hoofdvraag::class);
}
MODEL HOOFDVRAAG
public function subvraag()
{
return $this->hasMany(Subvraag::class);
}
public function toets() {
return $this->belongsTo(Toets::class);
}
MODEL SUBVRAAG
public function hoofdvraag() {
return $this->belongsTo(Hoofdvraag::class);
}
as i know , if you are creating an eloquent realtionship inside the models why you are creating the foreign key inside the migration all you need is create a column for it.
https://laravel.com/docs/5.8/eloquent-relationships#one-to-many

laravel 5.2 can't create foreign key while running migration

I get this error while trying to migrate:
SQLSTATE[HY000]: General error: 1005 Can't create table testing.#sql-1848_3ae (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table gallery add constraint gallery_user_id_foreign foreign key (user_id) references users (id))
[PDOException] SQLSTATE[HY000]: General error: 1005 Can't create table testing.#sql-1848_3ae (errno: 150 "Foreign key constraint is incorrectly formed")
here are my migrations:
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
class CreateGalleryTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('gallery', function (Blueprint $table) {
$table->increments('id');
$table->string('description')->nullable();
$table->integer('user_id');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('gallery');
}
}
I don't believe you can set a forgein key within the Schema::create();
Add this within your up method, but outside of the Schema::create();
Schema::table('gallery', function ($table) {
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
}
Also, consider adding the following to your down() function. I have run into issues trying to reset migrations and not working due to the Foreign Key Constraints.
$table->dropForeign('gallery_user_id_foreign');