Laravel : Migration with Foreign Key - mysql

I know this question has been ask a lot of time but i tried every solutions and it still give me an error.
I want to migrate my tables :
class CreateFichesTable extends Migration
{
public function up()
{
Schema::create('fiches', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('type');
$table->string('nom');
$table->string('description');
$table->string('image');
$table->integer('equipe_id')->unsigned();
$table->timestamps();
});
Schema::table('fiches', function(Blueprint $table)
{
$table->foreign('equipe_id')->references('id')->on('equipes');
});
}
}
And
class CreateEquipesTable extends Migration
{
public function up()
{
Schema::create('equipes', function (Blueprint $table) {;
$table->increments('id');
$table->string('nom');
$table->string('image');
$table->timestamps();
});
}
}
And I get :
Exception trace:
1 PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign
key constraint")
I tried to force using the engine "InnoDB" but still not working.
Any tip ?

When you create new migration file laravel automatically added in the start datetime like this 2018_08_10_111004_ for detect which migration must be create firstly. As you show in comments your migration files is 2018_08_31_141536_create_fiches_table.php and 2018_09_03_141649_create_equipes_table.php you must be change one of this migration for firstly called second migration the first. For example
2018_08_31_141536_create_fiches_table.php
2018_08_30_141649_create_equipes_table.php

Related

Laravel 7.4 cannot add foreign key constraint

So I'm creating a migration file following the template of my old one as follows:
create_banners_table (this one WORKED)
class CreateBannersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('banners', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('order');
$table->string('published');
$table->timestamps();
});
Schema::create('banner_translations', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('locale', 10)->index();
$table->string('title');
$table->string('url');
$table->foreignId('banner_id')
->constrained()
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('banner_translations');
Schema::dropIfExists('banners');
}
}
Here's the create_managements_table (this one FAILED):
class CreateManagementsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('managements', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('order');
$table->string('published');
$table->string('name');
$table->string('category')
->comment('board of commissioners', 'board of executives');
$table->timestamps();
});
Schema::create('management_translations', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('locale', 10)->index();
$table->string('description');
$table->string('title');
$table->foreignId('management_id')
->constrained()
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('management_translations');
Schema::dropIfExists('managements');
}
}
The problem is, when I tried to make another migration file based on that, I got this error:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `management_translations` add constraint `management_translations_management_id_foreign` foreign key (`management_id`) references `management` (`id`) on delete cascade)
As you can see both of the translation table references the big integer in their respective base table (so there is no type mismatch).
For further investigation, I ran SHOW ENGINE INNODB STATUS;
and checked the Latest Foreign Key Error and got the following:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2021-08-28 12:01:41 0x7f6f44091700 Error in foreign key constraint of table cemindo/#sql-200_7:
foreign key (`management_id`) references `management` (`id`) on delete cascade:
Cannot resolve table name close to:
(`id`) on delete cascade
Whether or not the word management countable is ambiguous so apparently Laravel treats it as uncountable in this case. That's to say that Laravel thinks the corresponding table name for management_id would be management not managements which is an uncommon plural form. Therefore you either should rename your base table to management or use the following foreign key sytnax:
Schema::create('management_translations', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('locale', 10)->index();
$table->string('description');
$table->string('title');
$table->foreignId('management_id')
->constrained('managements')
->onDelete('cascade');
});
Schema::create('banner_translations', function (Blueprint $table) {
$table->increments('banner_id')->unsigned(); //change this line
$table->string('locale', 10)->index();
$table->string('title');
$table->string('url');
$table->foreignId('banner_id')
->constrained()
->onDelete('cascade');
});
I think you should provide banner_id first and then provide foreignId.(same column name)
you can add foreign key reference as like below,
first create all the keys then at last declare the foreign key reference ... you can see this method at Laravel Doc's ... See First example of that link
Schema::create('managements', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('order');
$table->string('published');
$table->string('name');
$table->string('category')
->comment('board of commissioners','board of executives');
$table->timestamps();
});
Schema::create('management_translations', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('locale', 10)->index();
$table->string('description');
$table->string('title');
$table->unsignedBigInteger('management_id');
$table->foreign('management_id')
->references('id')
->on('managements');
->onDelete('cascade');
});
If you face any error using my solution let me know, I will update my answer
Thank you

Cannot create multiple Primary Keys on Migration for Laravel

I'm doing migrations for the DB of the enterprise I work for.
The issue is that the same table has 4 primary keys but this error is being throw by Laravel.
This is how my migrations look like:
Schema::create('ventas', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('empresa_id')->primary();
$table->integer('moneda_id')->primary();
$table->integer('user_id')->primary();
$table->foreign('empresa_id')->references('id')->on('empresas')->onDelete('restrict');
$table->foreign('moneda_id')->references('id')->on('monedas')->onDelete('restrict');
How can I solve this?
Thanks!
try this
public function up()
{
Schema::create('ventas', function (Blueprint $table) {
$table->id();
$table->foreignId('empresa_id')->nullable()->constrained()->onDelete('restrict');
$table->foreignId('moneda_id')->nullable()->constrained()->onDelete('restrict');
$table->foreignId('user_id')->nullable()->constrained()->onDelete('restrict');
$table->timestamps();
});
}

I have a table 'posts' which contains a foreign key 'user_id, how can i add that key to table on migration?

this is the migration
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->timestamps();
i have tried to do it with this lines
$table->bigInteger(‘user_id’)->unsigned()->nullable()->default(null);
$table->foreign(‘user_id’)->references(‘id’)->on(‘users’)->onDelete(‘cascade’);
what i did
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->integer(‘user_id’)->unsigned()->nullable()->default(null);
$table->foreign(‘user_id’)->references(‘id’)->on(‘users’)-
>onDelete(‘cascade’);
what i get
ErrorExceptionenter
Use of undefined constant ‘user_id’ - assumed '‘user_id’' (this will throw an Error in a future version of PHP)
#Mirage Three questions:
why are you using backticks instead of single quotes?
why are you using just $table->id(); when it should be $table->integer('id');?
why are you using $table->timestamps(); when it should be $table->timestamp('created');?
This migration with tweaks to be single quotes instead of backticks, correctly using $table->id(); and $table->timestamp('created'); works just fine for me:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Posts extends Migration
{
public function up()
{
if(!Schema::hasTable('posts')) {
Schema::connection('migrate')->create('testPosts', function (Blueprint $table) {
$table->integer('id');
$table->integer('user_id')->unsigned()->nullable()->default(null);
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamp('created');
});
}
}
public function down()
{
if(Schema::hasTable('posts')) {
Schema::connection('migrate')->dropIfExists('posts');
}
}
}

how to rename foreign key in Laravel

I want to rename the foreign key in Laravel.
This is how, I have created it:
Schema::create('holidays', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('account_id')->unsigned();
$table->date('holiday_date');
});
if (Schema::hasTable('accounts')) {
Schema::table(
'holidays',
function (Blueprint $table) {
$table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade');
}
);
}
And now, I want to change account_id to engagement_id. How to do that?
It should be something like this :
Note : Before Renaming Foreign, You Must Need To Delete Old Foreign And Assign New One
class RenameColumn extends Migration
{
public function up()
{
Schema::table('holidays', function(Blueprint $table) {
$table->dropForeign('holidays_account_id_foreign');
$table->renameColumn('account_id', 'engagement_id');
$table->foreign('engagement_id')->references('id')->on('accounts')->onDelete('cascade');
});
}
public function down()
{
Schema::table('holidays', function(Blueprint $table) {
$table->dropForeign('holidays_engagement_id_foreign');
$table->renameColumn('account_id', 'engagement_id');
$table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade');
});
}
}
What #rborum explained requires doctrine/dbal package to be installed. Else you could directly execute sql query to rename your key or do any other changes.
I was able to do this without dropping the column.
Very simply:
public $oldIndex = 'old_constraint_name_foreign';
public $newIndex = 'new_constraint_name_foreign';
public $oldColumn = 'old_column_name';
public $newColumn = 'new_column_name';
Schema::table('my_table', function (Blueprint $table) {
$table->renameIndex($this->oldIndex, $this->newIndex);
$table->renameColumn($this->oldColumn, $this->newColumn);
});
You need to make a new migration with:
php artisan make:migration rename_column
With this inside:
class RenameColumn extends Migration
{
public function up()
{
Schema::table('accounts', function(Blueprint $table) {
$table->renameColumn('account_id ', 'engagement_id');
});
}
public function down()
{
Schema::table('accounts', function(Blueprint $table) {
$table->renameColumn('account_id ', 'engagement_id');
});
}
}
Then execute your migration:
php artisan migrate
If you do not already have it, you will need Doctrine. You can get this via composer with
composer require doctrine/dbal

Error NULL DEFAULT NULL Laravel migration with MariaDB

I have the following migration, where I'm adding an extra column in a table:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddTenantIdToPeopleTable extends Migration
{
public function up()
{
/*
* Need to create the column as null and then mark it as non-null to
  * avoid SQLite problem General error: 1 Can not add to NOT NULL column with default value NULL
*/
Schema::table('people', function (Blueprint $table) {
$table->integer('tenant_id')->nullable()->unsigned();
$table->index('tenant_id');
});
Schema::table('people', function (Blueprint $table) {
$table->integer('tenant_id')->nullable(false)->change();
});
}
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::table('people', function (Blueprint $table) {
$table->dropColumn('tenant_id');
});
Schema::enableForeignKeyConstraints();
}
}
I can run this migration with PostgreSQL, SQLite and MySQL without any errors, but when I try to run with Maria DB, this error happens:
Error
I tried some things but nothing works.
I've managed to get this thing working.
I just added the "->default(null)"
I did this:
public function up()
{
Schema::table('people', function (Blueprint $table) {
$table->integer('tenant_id')->nullable()->unsigned();
$table->index('tenant_id');
});
Schema::table('people', function (Blueprint $table) {
$table->integer('tenant_id')->nullable(false)->default(null)->change();
});
}