Doing the migrations I got this error:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table books add constraint books_writer_id_foreign foreign key (writer_id) references writers (id))
I've tried a lot of things but noone looks to work.
2018_02_18_3165165_create_books_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBooksTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('name');
$table->text('description');
$table->integer('numPages');
$table->enum('language', ['spanish', 'english']);
$table->date('wrote_date')->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
});
Schema::table('books', function (Blueprint $table) {
$table->integer('writer_id')->unsigned();
$table->foreign('writer_id')->references('id')->on('writers');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('books');
}
}
2018_02_18_192915_create_writers_table
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateWritersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('writers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description');
$table->string('nationality');
$table->date('year_date')->nullable();
$table->date('dead_date')->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('writers');
}
}
Edit: The error was because the first migration was the books, and then the writers causing that the error.
Sometimes based on my experience too close timestamps will break the code and will throw an exception because program thinks that writers table is created after books table try to change writers_table timestamp something like: 2018_02_16_31615
Make it unsignedInteger because you're using increments()
$table->unsignedInteger('writer_id')->nullable();
change in migration source your_table_name
Schema::create('your_table_name', function (Blueprint $table) {
$table->BigIncrements('id');
to
Schema::create('your_table_name', function (Blueprint $table) {
$table->increments('id');
Move this line to the first closure:
$table->integer('writer_id')->unsigned();
Put it right after:
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
Also, you need to add timestamps to both migration files so Laravel first create the writers table and then the books table:
2018_02_01_000000_create_writers_table.php
2018_02_02_000000_create_books_table.php
Related
How to solve this error? SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table invoices add constraint invoices_form_id_foreign foreign key (form_id) references forms (id) on delete cascade)
I get it after: php artisan migrate:fresh
For foreign keys in invoices get this error. 3 foreign keys generate error but one for user_id is good and works fine. I tried all solutions and didn't worked. Please help me.
2014_10_12_000000_create_users_table.php
<?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->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('surname')->nullable();
$table->string('showname')->nullable();
$table->string('business')->nullable();
$table->string('NIP')->nullable();
$table->string('PESEL')->nullable();
$table->string('address')->nullable();
$table->string('city')->nullable();
$table->string('postalcode')->nullable();
$table->string('phone')->nullable();
$table->string('comments')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
2020_07_23_104440_invoices.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Invoices extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('invoices', function (Blueprint $table) {
$table->increments('id');
$table->string('invoicenumber')->nullable();
$table->date('invoicedate')->nullable();
$table->date('selldate')->nullable();
$table->integer('user_id')->unsigned()->nullable();
$table->integer('form_id')->unsigned()->nullable();
$table->integer('currency_id')->unsigned()->nullable();
$table->integer('proform_id')->unsigned()->nullable();
$table->string('paymentmethod')->nullable();
$table->date('paymentdate')->nullable();
$table->string('status')->nullable();
$table->string('comments')->nullable();
$table->string('city')->nullable();
$table->string('paid')->nullable();
$table->string('autonumber')->nullable();
$table->string('automonth')->nullable();
$table->string('autoyear')->nullable();
$table->timestamps();
});
Schema::table('invoices', function (Blueprint $table){
$table->foreign('user_id')
->references('id')
->on('users');
$table->foreign('form_id')
->references('id')
->on('forms');
$table->foreign('currency_id')
->references('id')
->on('currencys');
$table->foreign('proform_id')
->references('id')
->on('proforms');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('invoices');
}
}
2020_07_27_090356_proforms.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Proforms extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('proforms', function (Blueprint $table) {
$table->increments('id');
$table->string('proformnumber')->nullable();
$table->date('proformdate')->nullable();
$table->date('selldate')->nullable();
$table->integer('user_id')->unsigned()->nullable();
$table->string('paymentmethod')->nullable();
$table->date('paymentdate')->nullable();
$table->string('status')->nullable();
$table->string('comments')->nullable();
$table->timestamps();
});
Schema::table('proforms', function (Blueprint $table){
$table->foreign('user_id')
->references('id')
->on('users');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('proforms');
}
}
2020_07_28_091856_forms.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Forms extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('forms', function (Blueprint $table) {
$table->increments('id');
$table->string('form')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('forms');
}
}
2020_07_28_091919_currencys.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Currencys extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('currencys', function (Blueprint $table) {
$table->increments('id');
$table->string('currency')->nullable();
$table->string('course')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('currencys');
}
}
Here is what might be happening with your migrations.
1. Check the the primary and foreign key type. If user primary key ID is type $table->increments('id'); // bigInteger, then the foreign key should be bigInteger as well $table->bigInteger('user_id');
2. Please check your migration order. For example table invoices has foreign key fromforms table. During the migration, forms table should migrate first. And to make it make it happen, just rename the migration file(numeric section of file name) so that the forms.
because when excuting the migration reach this line:
$table->foreign('form_id')->references('id')->on('forms');
in 2020_07_23_104440_invoices file
the forms table has not been created yet
you should make a new migration to make that relation
Schema::table('invoices', function (Blueprint $table){
$table->foreign('form_id')
->references('id')
->on('forms');
}
this migration should be after 2020_07_28_091856_forms.php migration ...
The problem is the order of the migration
see the order
2020_07_23_104440_invoices.php
2020_07_28_091856_forms.php
when the invoices table is created there will be no forms table as it is created afterwards. So the error is because you are trying to create relationship between non existing forms table id field while creating invoices table.
What you can do is create a new migration file for attaching the relationship only.
here is how to do it
delete add foreign key from. remove this part from 2020_07_23_104440_invoices.php
$table->foreign('form_id')
->references('id')
->on('forms');
after removing create seperate migration for adding forign key
run
php artisan make:migration add_form_foreign_key_to_invoices
It will generate the new migration file. Update it like this.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddFormForeignKeyToInvoices extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('invoices', function (Blueprint $table) {
$table->foreign('form_id')->references('id')->on('forms');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('invoices', function (Blueprint $table) {
$table->dropForeign('form_id');
});
}
}
I'm trying to create foreign keys in Laravel however when I migrate my table using artisan i am thrown the following error:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `products` add constraint `products_user_id_foreign` foreign key (`user_id`) references `users` (`id`))
This is my user migration
<?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->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('surname')->nullable();
$table->string('showname')->nullable();
$table->string('business')->nullable();
$table->string('NIP')->nullable();
$table->string('PESEL')->nullable();
$table->string('address')->nullable();
$table->string('city')->nullable();
$table->string('postalcode')->nullable();
$table->string('phone')->nullable();
$table->string('comments')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
This is my products migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('detail')->nullable();
$table->integer('user_id')->nullable();
$table->string('category')->nullable();
$table->date('launchdate')->nullable();
$table->date('expirationdate')->nullable();
$table->integer('billingperiod')->nullable();
$table->integer('renewalprice')->nullable();
$table->integer('internalcost')->nullable();
$table->string('status')->nullable();
$table->timestamps();
});
Schema::table('products', function (Blueprint $table){
$table->foreign('user_id')
->references('id')
->on('users');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
Please help me. I don't know what to do with this. I changed DB engine to Inno DB in databaase.php but it didn't helped at all.
Laravel's increments() creates an "Auto-incrementing UNSIGNED INTEGER (primary key) equivalent column.". You foreign key column user_id has to be of the exact same type as the column it is referencing.
In your CreateProductsTable migration, change
$table->integer('user_id')->nullable();
to
$table->integer('user_id')->unsigned()->nullable();
and try again.
https://laravel.com/docs/7.x/migrations#creating-columns
I am trying to add foreign key constraints to my database tables via Laravel Migrations, but I always get an error like this:
Illuminate\Database\QueryException :
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
(SQL: alter table `tasks` add constraint `tasks_task_list_id_foreign` foreign key (`task_list_id`) references `task_lists` (`id`))
The migration for the tasks table looks like this:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTasksTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->integer('task_list_id')->unsigned()->index();
$table->string('task');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('task_list_id')->references('id')->on('task_lists');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('tasks');
}
}
And that's the task_lists table:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTaskListsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('task_lists', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->string('name');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('task_lists');
}
}
I can't figure out the problem and would highly appreciate any kind of help.
Thank you in advance!
You have to check the order of your migrations. Obviously, you have to run de Users table migration before the Tasks table migration. If the problem persist, try to make something like this inside the up() method and after the (Schemma::create):
Schema::table('task_lists', function($table){
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
I am very new at Laravel! But I'm trying. Here is were I could use some help;
I have a posts table. I have a user table. But I forgot to add a foreign key in the posts table that links to the user id.
The create users table migration:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
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::dropIfExists('users');
}
}
The create posts table migration:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
I have created the new migration file:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterTablePostsAddForeignUser extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
// I HAVE NO IDEA WHAT TO DO NEXT
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
}
}
I have no idea how to fill up the "public function up()" method here! If anyone can help! It will be much appreciated!
I tried this and this worked for me.
Schema::table('posts', function (Blueprint $table) {
$table->integer('user_id')->nullable()->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
Here When you adding foreign key, by default it will have a Null value.This 'null referencing' may cause the issue. Using nullable() foreign key will avoid that issue.
See the docs here
You need to install doctraine/dbal before modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the specified adjustments to the column and the you should try what I found on this SO post
Schema::table('posts', function (Blueprint $table) {
$table->integer('user_id')->unsigned()->change();
$table->foreign('user_id')->references('id')->on('users');
});
change() method for change structure of column
after this run the artisan command
php artisan migrate
if this doesn't work for you shoot the comment here! :)
I am trying to add a foreign key in my posts table to reference the id in the users table. Here are my migrations, the users table is the default one packed with laravel so the timestamps are from NOV 2014 however the posts is one I created. Any help greatly appreciated.
Thanks a lot :)
Users migration
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('name')->unique();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
posts migration
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('title');
$table->string('section');
$table->string('body');
$table->date('post_created_date');
$table->integer('author_id')->unsigned()->after('id');
$table->foreign('author_id')->references('id')->on('users');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('posts');
}
}
Every time I migrate I get the following error:
If you are creating a table, you don't want to use after as it will create a syntax error. Just place the column where you want it. I believe after will only work for alter table statements.
Schema::create('posts', function (Blueprint $table) {
$table->increments('id'); // Unsigned is assumed for increments so I removed that as well
$table->integer('author_id')->unsigned();
$table->string('title');
$table->string('section');
$table->string('body');
$table->date('post_created_date');
$table->timestamps();
$table->foreign('author_id')->references('id')->on('users');
});
Then in your model, you'd setup the relationship to your users table like so...
public function author()
{
return $this->belongsTo(User::class, 'author_id');
}
Feel free to rename the function however you want, I usually prefer to name it something that matches the foreign key.
Then you'd use it like $post->author->name.
In your CreatePostsTable class, can you try this ?
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('author_id')->unsigned();
$table->string('title');
$table->string('section');
$table->string('body');
$table->date('post_created_date');
$table->timestamps();
});
Schema::table('posts', function($table) {
$table->foreign('author_id')->references('id')->on('users');
});
}