FK in table is not working while migrate - php

When I create a migration for table at that time there is an issue with its through following error.
Illuminate\Database\QueryException : SQLSTATE[HY000]: General
error: 1005 Can't create table yourwebs_veridocedu.#sql-2c46_8e
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL:
alter table user_role_mappings add constraint
user_role_mappings_user_id_foreign foreign key (user_id)
references users (id) on delete cascade)
Migration for userrolemapping table:
public function up()
{
Schema::create('user_role_mappings', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('group_id');
$table->integer('roleid');
$table->integer('status');
$table->integer('createdby');
$table->integer('modifiedby');
$table->string('publicguid');
$table->string('privateguid');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade');
});
}
Migration for Role table :
public function up()
{
Schema::create('userroles', function (Blueprint $table) {
$table->increments('id');
$table->string('rolename');
$table->integer('status')->default(1);
$table->integer('createdby')->default(1);
$table->integer('modifiedby')->default(1);
$table->string('publicguid');
$table->string('privateguid');
$table->timestamps();
});
}
Usertable migration:
<?php
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->engine = 'InnoDB';
$table->increments('id');
$table->string('name');
$table->string('email',150)->unique();
$table->string('password');
$table->integer('roleid')->unsigned();
$table->rememberToken();
/*Common Fields*/
$table->integer('status');
$table->integer('createdby');
$table->integer('modifiedby');
$table->string('publicguid');
$table->string('privateguid');
$table->timestamps();
/*From other table */
$table->foreign('roleid') ->references('id')->on('userroles')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
FK in table is not working which migrate.

increments columns are unsigned, your foreign key columns need to have the same signature. So you should change the columns like so:
$table->integer('user_id')->unsigned();
$table->integer('group_id')->unsigned();

Try something as given below.
$table->integer('user_id')->unsigned()->index();
$table->integer('group_id')->unsigned()->index();

Both tables have to use the InnoDB engine and the column types have to match:
Schema::create('user_role_mappings', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->unsignedInteger('user_id');
$table->unsignedInteger('group_id');
});

Related

SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'proform_id' doesn't exist in table

After php artisan migrate:fresh I get error:
SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'proform_id' doesn't exist in table (SQL: alter table proforms add constraint proforms_proform_id_foreign foreign key (proform_id) references proforms (id) on delete cascade)
This is migration which generates error:
2020_08_08_093303_create_dynamic_field.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDynamicField extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('dynamic_fields', function (Blueprint $table) {
$table->increments('id');
$table->string('id_pozycji')->nullable();
$table->string('name')->nullable();
$table->string('PKWIU')->nullable();
$table->integer('quantity')->nullable();
$table->integer('unit')->nullable();
$table->integer('netunit')->nullable();
$table->integer('nettotal')->nullable();
$table->integer('VATrate')->nullable();
$table->integer('grossunit')->nullable();
$table->integer('grosstotal')->nullable();
$table->integer('proform_id')->nullable();
$table->timestamps();
$table->time('deleted_at')->nullable();
});
Schema::table('proforms', function (Blueprint $table){
$table->foreign('proform_id')
->references('id')
->on('proforms')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('dynamic_fields');
}
}
This is migration asociated with it:
2020_07_29_101958_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->integer('proformnumber')->nullable();
$table->date('proformdate')->nullable();
$table->date('selldate')->nullable();
$table->integer('user_id')->unsigned()->nullable();
$table->integer('form_id')->unsigned()->nullable();
$table->integer('currency_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('autonumber')->nullable();
$table->integer('automonth')->nullable();
$table->integer('autoyear')->nullable();
$table->string('name')->nullable();
$table->string('PKWIU')->nullable();
$table->integer('quantity')->nullable();
$table->integer('unit')->nullable();
$table->integer('netunit')->nullable();
$table->integer('nettotal')->nullable();
$table->integer('VATrate')->nullable();
$table->integer('grossunit')->nullable();
$table->integer('grosstotal')->nullable();
$table->timestamps();
$table->time('deleted_at')->nullable();
});
Schema::table('proforms', function (Blueprint $table){
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('form_id')
->references('id')
->on('forms')
->onDelete('cascade');
$table->foreign('currency_id')
->references('id')
->on('currencys')
->onDelete('cascade');
});
This looks odd to me:
Schema::table('proforms', function (Blueprint $table) {
$table->foreign('proform_id')
->references('id')
->on('proforms')
->onDelete('cascade');
});
It looks like you are trying to add a foreign key with a reference to it's own table.
There is no proform_id on the proforms table. This statement needs to be run on the dynamic_fields table.
Schema::table('dynamic_fields', function (Blueprint $table) {
$table->foreign('proform_id')
->references('id')
->on('proforms')
->onDelete('cascade');
});
Try adding foreignId instead of just foreign like so:
Schema::table('proforms', function (Blueprint $table){
$table->foreignId('user_id')
->references('id')
->on('users')
->onDelete('cascade');

Problem SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

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

General error: 1215 Cannot add foreign key constraint in laravel

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

Can't add foreign key Laravel

I have 2 tables (regions & categories) , I wanted to have a foreign key in regions table this is my migration file :
public function up()
{
Schema::create('regions', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('nom');
$table->text('description');
$table->integer('vote');
$table->string('securite');
$table->integer('idCat')->unsigned()->change();
$table->foreign('idCat')->references('idCat')->on('categories');
$table->timestamps();
});
}
the table 'categorie' looks like this :
public function up()
{
Schema::create('categories', function (Blueprint $table) {
//$table->engine = 'InnoDB';
$table->increments('idCat');
$table->String('description');
$table->timestamps();
});
}
But I got this error : Syntax error or access violation: 1072 Key column 'idCat'
doesn't exist in table (SQL: alter table regions add constraint regions_
idcat_foreign foreign key (idCat) references categories (idCat))
Canyou help me please ?
Make sure you get rid of the change(), the column is not there yet.. The following code works perfectly for me...
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Test extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
//$table->engine = 'InnoDB';
$table->increments('idCat');
$table->String('description');
$table->timestamps();
});
Schema::create('regions', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('nom');
$table->text('description');
$table->integer('vote');
$table->string('securite');
$table->integer('idCat')->unsigned();
$table->foreign('idCat')->references('idCat')->on('categories');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('regions');
Schema::drop('categories');
}
}

Laravel 5.2 Foreign Key fails

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');
});
}

Categories