Skip to content
This repository has been archived by the owner on Dec 10, 2018. It is now read-only.

General error: 1215 Cannot add foreign key constraint when using relations #83

Closed
basepack opened this issue Oct 31, 2018 · 2 comments
Closed

Comments

@basepack
Copy link

Hi,

I am getting this error when running: php artisan migrate:refresh --seed. If I change back to normal ids I do not get this error.

Full error:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter tableinvoicerowsadd constraintinvoicerows_invoice_id_foreign foreign key (invoice_id) references invoices (id) on delete cascade)

My old migrations:

// Invoices migration
Schema::create( 'invoices', function ( Blueprint $table ) {
	$table->increments( 'id' );
}
// Invoicerows migration
Schema::create( 'invoicerows', function ( Blueprint $table ) {
	$table->increments( 'id' );

	$table->integer( 'invoice_id' )->unsigned()->nullable();
	$table->foreign( 'invoice_id' )->references( 'id' )->on( 'invoices' )->onDelete( 'cascade' );
}

New migration after installing `spatie/laravel-binary-uuid':

// new Invoices migration
Schema::create( 'invoices', function ( Blueprint $table ) {
	$table->uuid('uuid');
        $table->primary('uuid');
}
// New Invoicerows migration
Schema::create( 'invoicerows', function ( Blueprint $table ) {
	$table->uuid('uuid');
        $table->primary('uuid');

	$table->integer( 'invoice_uuid' )->unsigned()->nullable();
	$table->foreign( 'invoice_uuid' )->references( 'uuid' )->on( 'invoices' )->onDelete( 'cascade' );
}

When I now run php artisan migrate:refresh --seed I get that error.

I have tried to add my original id field: $table->increments( 'id' ); but I suppose you do not need an id field anymore when using binary uuids?

@vpratfr
Copy link
Collaborator

vpratfr commented Oct 31, 2018

This is the culprit:

$table->integer( 'invoice_uuid' )->unsigned()->nullable();

Should be

$table->uuid( 'invoice_uuid' )->nullable();

@basepack
Copy link
Author

@vpratfr, great catch! It was a long day I suppose 😄

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants