Laravel-5-Generators-Extended
Laravel-5-Generators-Extended copied to clipboard
Cannot add foreign key constraint (mysql)
When creating a schema which includes a foreign key, if you forget to add the "unsigned" option to the key, you will get a mysql error when you try to run the migration.
For instance, the README has an example regarding foreign keys, but before we use it, we need to setup the users table, so I'll do a dumb one here:
php artisan make:migration:schema create_users_table --schema="fullname:string"
This generates:
Schema::create('users', function(Blueprint $table) {
$table->increments('id');
$table->string('fullname');
$table->timestamps();
);
Fine and dandy. (Note, the "increments" above creates an unsigned integer field in mysql. This is important).
So, now we move on to the example given in the docs for making a schema which relates to this new users table...
php artisan make:migration:schema create_posts_table --schema="user_id:integer:foreign, title:string, body:text"
Which generates the following:
Schema::create('posts', function(Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->string('title');
$table->text('body');
$table->timestamps();
);
Running this migration, you will find it will bark at you saying
General error: 1215 Cannot add foreign key constraint"
To solve the problem on the fly, just go into the create_posts_table migration file and change one line:
// $table->integer('user_id');
$table->integer('user_id')->unsigned();
Since I've not done a PR before, and don't have the time at this very moment to learn, I'll leave this up to someone else to do unless (a) it's not fixed quickly, (b) I get annoyed enough by it and (c) I get the time to learn how to do PRs. :)
Hopefully this is helpful and will spark a change.
Cheers.
Simply marking user_id in create_posts_table as unsigned does the trick as well without having to manually modify the migration
php artisan make:migration:schema create_posts_table --schema="user_id:integer:unsigned:foreign, title:string, body:text"
It might be easier if any integer tagged with foreign would automatically be marked unsigned.
Hi guys - I know this is very very old, but do you guys still use this package? If so, let me know if this is still an issue, and something that is fixable. We're trying to close all issues&PRs and get v2 out the door soon https://github.com/laracasts/Laravel-5-Generators-Extended/pull/170 so this would be a great time to have this settled.
Cheers!
Yes @tabacitu We are still using the package. and a it is mentioned above, most of foreign keys are based in id.. this will simplify the work so much...