Foreign keys on laravel - mysql

I'm trying to work with foreign keys on Laravel. It's quite simple how to add foreign key on table. But if table can contain more than one foreign key, for example:
There is tables:
Building
id
name
companies(can be more than one)
and other table is:
Companies
id
name
As I remember from good practices, I should create other table like building_company with columns
building_id
company_id
If it's in good way, how Model of this 3rd table should be named and used, or maybe in Laravel there is other solutions for multiple FKs?
Thank you

Building table
public function up()
{
Schema::create('Building', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('companies');
$table->timestamps();
});
}
Companies table
public function up()
{
Schema::create('Companies', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
building_company table
public function up()
{
Schema::create('building_company', function (Blueprint $table) {
$table->increments('id');
$table->integer('building_id')->references('id')->on('Building')->onDelete('cascade');
$table->integer('company_id')->references('id')->on('Companies')->onDelete('cascade');
$table->timestamps();
});
}

Establish n:n relationship
Schema::create('building_companies', function (Blueprint $table) {
$table->integer('company_id')->unsigned();
$table->integer('building_id')->unsigned();
$table->foreign('building_id')
->references('id')
->on('building')
->onDelete('cascade');
$table->foreign('company_id')
->references('id')
->on('companies')
->onDelete('cascade');
});

You dont use a Model::class for a pivot table in Laravel because it doesn't support composite primary key,
You can declare a Pivot::class (Illuminate\Database\Eloquent\Relations\Pivot)
But most of the times (especially if there is only the ids) you dont declare the pivot class, You use ManyToMany (belongsToMany()) relation between the two main models (Building & Company in your case)

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

SQLSTATE[HY000]: General error: 1005 Can't create table `test`.`members` (errno: 150 "Foreign key constraint is incorrectly formed")

I'm using my migrations in Laravel to create the relationships between tables, and I have 4 tables: users, members, member_skills, and skills. I have the following code for the users table:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->boolean('admin');
});
}
the members table:
public function up()
{
Schema::create('members', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('name');
$table->string('status');
$table->date('date')->nullable();
$table->text('project')->nullable();
$table->date('start')->nullable();
$table->foreign('name')->references('name')->on('users');
});
}
the member_skills table:
public function up()
{
Schema::create('member_skills', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('name');
$table->string('skill');
$table->foreign('name')->references('name')->on('members');
});
}
and the skills table:
public function up()
{
Schema::create('skills', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('skill');
$table->text('description');
$table->foreign('skill')->references('skill')->on('member_skills');
});
}
However, running my migrations results to (errno: 150 "Foreign key constraint is incorrectly formed"). I have read that changing the migration order should fix the problem, so I have arranged the 4 tables to be migrated in the order of users, members, member_skills, and skills, but I am still receiving the same error. Is there anything else I'm doing wrong?
Here is the right way todo this
public function up()
{
Schema::create('members', function (Blueprint $table) {
...
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
}
public function up()
{
Schema::create('member_skills', function (Blueprint $table) {
...
$table->unsignedBigInteger('member_id');
$table->foreign('member_id')->references('id')->on('members');
});
}
public function up()
{
Schema::create('skills', function (Blueprint $table) {
...
$table->unsignedBigInteger('member_skill_id');
$table->foreign('member_skill_id')->references('id')->on('member_skills');
});
}
more:https://laravel.com/docs/8.x/migrations#foreign-key-constraints
You should try using the id of the member table as the foreign key rather than the name in the member_skills schema
public function up()
{
Schema::create('member_skills', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('member_id');
$table->string('skill');
$table->foreign('member_id')->references('id')->on('members');
});
}
You are getting this error because you are trying to reference name in the member table which is already a foreign key to the users table.
You can access the name of the member through the id foreign key in your blade.

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

Why is creating Foreign Key in Laravel 5.8 failing?

The migration script below was running smoothly in an older version of Laravel but I added it to my fresh Laravel 5.8 and ran the script. I'm getting Error: foreign key was not formed correctly
Evaluation Migration:
public function up() {
Schema::create('evaluation', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
Users Migration:
public function up() {
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
});
}
As we discussed in the comments above, a foreign key column must be the same data type as the primary key it references.
You declared your user.id primary key as $table->bigIncrements('id') which becomes BIGINT UNSIGNED AUTO_INCREMENT in MySQL syntax.
You must declare the foreign key as $table->unsignedBigInteger('user_id') which will become BIGINT UNSIGNED in MySQL, making it compatible with being a foreign key to the user.id column.
update your `integer('user_id')` to `bigInteger('user_id')`
public function up() {
Schema::create('evaluation', function (Blueprint $table) {
$table->increments('id');
$table->bigInteger('user_id')->unsigned()->index();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}

Laravel : Migration with Foreign Key

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