Table not found when seeding - php

Below are my migrations
The users table have a relation with the customer table
In user:
$table->integer('customer_id')->unsigned();
$table->foreign('customer_id')->references('id')->on('customers');
When i call php artisan migrate:refresh --seed, artisan given me the following error:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table `users` add constraint `users_customer_id_foreign` foreign ke
y (`customer_id`) references `customers` (`id`))
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
Because the customers table does not exists... (obvious)
Is there a way to solve this problem? I know changing the date of the files will fix this but there should be a beter approach

You have to create the table you're referencing to before adding the foreign key. A solution would be to remove the foreign key constraint from your user table migration and create a new migration which adds the foreign key constraints.

Try to make it separately.
public function up()
{
Schema::create('users', function(Blueprint $table) {
$table->increments('id');
$table->integer('costumer_id')->unsigned();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::table('users', function($table) {
$table->foreign('costumer_id')->references('id')->on('costumers');
});
}
Another thing you can try(since laravel 5.3):
unsignedInteger('column_name') instead of ('column_name')-unsigned()

If you had set one field as "Unsigned" and other one not. Once you should set both columns to Unsigned it works.

Related

SQLSTATE[HY000]: General error: 1005 Can't create table Laravel 8

Schema::create('menus', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->string('slug')->unique();
$table->integer('price');
$table->text('description');
$table->timestamps();
});
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('slug')->unique();
$table->timestamps();
});
Schema::create('category_menu', function (Blueprint $table) {
$table->increments('id');
$table->integer('menu_id')->unsigned()->nullable();
$table->foreign('menu_id')->references('id')
->on('menus')->onDelete('cascade');
$table->integer('category_id')->unsigned()->nullable();
$table->foreign('category_id')->references('id')
->on('categories')->onDelete('cascade');
$table->timestamps();
});
When I run php artisan:migrate, I get the following error.
SQLSTATE[HY000]: General error: 1005 Can't create table `mieaceh`.`category_menu` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `category_menu` add constraint `category_menu_menu_id_foreign` foreign key (`menu_id`) references `menus` (`id`) on delete cascade)
This is due to mismatch of datatype of foreign key column and the referenced column most likely
When you create a primary key with $table->id() the datatype of the auto incrementing id column is unsignedBigInteger so you must have foreign key also with the same datatype
Schema::create('category_menu', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('menu_id');
$table->foreign('menu_id')->references('id')
->on('menus')->onDelete('cascade');
$table->unsignedBigInteger('category_id');
$table->foreign('category_id')->references('id')
->on('categories')->onDelete('cascade');
$table->timestamps();
});
You shouldn't make the columns in a pivot table nullable for the foreign keys to maintain data integrity.
Also be consistent with the datatype for primary key columns as well as definitions - when using $table->id() keep that consistent across all migrations for all tables. That way you will have less chances of mismatch when defining foreign keys as $table->unsignedBigInteger()
laravel migrations files contains a datetime slug that determine which file will be migrated first
notice the order
2021_10_11_101533_create_posts_table.php
2014_10_12_000000_create_users_table.php
when you run
php artisan migrate
posts table will be migrated first and it contains a foriegn key
user_id
which references a primary key on users table
id
but the users table doesn't exists yet, to fix this issues change the files names and make sure users table migrate first like this
notice the order
2014_10_10_000000_create_users_table.php
2021_10_11_101533_create_posts_table.php
short pattern for declaring a foreign key
$table->foreignId('user_id')->constrained()->cascadeOnDelete();

Laravel 5.3 - Foreign key constraint is incorrectly formed

Using Laravel 5.3 and Eloquent model, Trying to make a user role model.
the main schema that I have 2 tables users and roles, each user have a role and every role have many users (one to many relationship).
when i'm trying to make a foreign key in user table that references the id in roles table it gives me this error
In Connection.php line 647:
SQLSTATE[HY000]: General error: 1005 Can't create table
mydata.#sql-7e0_71 (errno: 150 "Foreign key constraint is incorrectly
formed") (SQL: alter table "user" add constraint
"user_role_id_foreign" foreign key ("role_id") references roles("id"))
In Connection.php line 449:
SQLSTATE[HY000]: General error: 1005 Can't create table
mydata.#sql-7e0_71 (errno: 150 " Foreign key constraint is
incorrectly formed")
Note: I'm using artisan command migrate, and I've tried these answers 1,2
here is my up() function for my user migration
public function up()
{
Schema::create('user', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->integer('role_id')->unsigned();
$table->string('remember_token')->nullable();
$table->timestamps();
$table->foreign('role_id')->references('id')->on('role');
});
}
and for role table
public function up()
{
Schema::create('role', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description');
$table->timestamps();
});
}
You are trying to add a foreign key that have a reference on the roles table (->on('roles')), but in your migration file you are creating a table named role (Schema::create('role', ...).
You need to match those.
Either changed the name of the role table to roles or your reference to the role table.

Adding a foreign key constraint with a Laravel Migration

I have started a new Laravel 5.5 project and I am receiving the following error when trying to add a foreign key to my users table:
General error: 1215 Cannot add foreign key constraint (SQL: alter table users add constraint users_organization_id_foreign foreign key (organization_id) references organizations (id) on delete cascade)
Here is the migration code for the organization table:
Schema::create('organizations', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('subdomain')->nullable();
$table->timestamps();
$table->softDeletes();
});
Here is the migration code for the users table:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->integer('organization_id')->unsigned();
$table->foreign('organization_id')->references('id')->on('organizations');
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->timestamps();
$table->softDeletes();
});
I have researched this error online and the common thing to make sure of are that the data types are the same. From what I can see, they are the same. What's even crazier is that if I run this query in the database directly it works:
alter table `users` add constraint `users_organization_id_foreign` foreign key (`organization_id`) references `organizations` (`id`)
By default, in each Laravel fresh installation users table is created first. But since you're adding a constraint in this table, you need to create organizations table first.
So, put organizations table migration before users table migration by changing organizations migration date in the file name:
2014_01_01_000000_create_organizations_table.php
Going along with Alexey's answer. I would also suggest that you enable/disable foreign key constraints before you run your migrations:
Schema::disableForeignKeyConstraints();
// Your migration code.
Schema::enableForeignKeyConstraints();
This way you don't need to rename your migration files.

mysql foreign key error in Laravel 5.1

I have created two migrations:
Migration 1
Schema::create('responders', function (Blueprint $table) {
$table->increments('id');
$table->string('user_id');
$table->double('latitude', 10, 6);
$table->double('longitude', 10, 6);
$table->timestamps();
});
Migration 2
Schema::create('devices', function (Blueprint $table) {
$table->increments('id');
$table->string('user_id');
$table->string('device_id');
$table->string('device_token');
$table->timestamps();
$table->foreign('user_id')
->references('user_id')
->on('responders')
->onDelete('cascade');
});
When I start migration the error message is being thrown:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
(SQL: alter table devices add constraint devices_user_id_foreign
foreign key (user_id) references responders (user_id) on delete
cascade)
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
I specifically took care that the data types are the same. In this case both are of type string. Why does the foreign key can't be established?
A foreign key is a column (or columns) that references a column (most
often the primary key) of another table. The purpose of the foreign
key is to ensure referential integrity of the data. In other words,
only values that are supposed to appear in the database are permitted.
Here user_id in responders table isn't a key that's why it's showing this error.

How to run php artisan migrate on a db with a lot of tables and data without previous migrations in Laravel 4?

I have created a lot of tables and I have a lot of data in my db's tables already.
I haven't used migrations so far. But right now I would like to, in this case where I need to set foreign keys using this code:
public function up()
{
Schema::create('role_user', function(Blueprint $table)
{
$table->increments('id');
$table->integer('role_id')->unsigned()->index();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
But If I run php artisan migrate I get this error:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table `role_user` add constraint role_user_role_id_foreign foreign
key (`role_id`) references `roles` (`id`) on delete cascade)
migrate [--bench[="..."]] [--database[="..."]] [--force] [--path[="..."]] [--pac
kage[="..."]] [--pretend] [--seed]
I have roles and users table already and id is set as the primary key.
Any idea how to make this auto creation of the table from the schema in the migration file in my db happen?

Categories