php - One to one relationship error on can't alter table when run artisan command -
i've multiple packages , users can have 1 package @ time, not multiple. so, i've created 1 one relationship , added foreign key in users table.
here's relevant users table:
public function up() { schema::create('users', function (blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password', 60); $table->string('role'); $table->unsignedinteger('package_id'); $table->remembertoken(); $table->nullabletimestamps(); $table->foreign('package_id') ->references('id') ->on('packages'); }); }
and here's packages table:
public function up() { schema::create('packages', function (blueprint $table) { $table->increments('id'); $table->string('name'); $table->integer('price'); $table->integer('space'); $table->string('space_type'); $table->string('trial')->nullable(); $table->string('trial_period')->nullable(); $table->string('password_protected_links')->nullable(); $table->nullabletimestamps(); }); }
however, when ran php artisan migrate:refresh
appeared following error:
[illuminate\database\queryexception] sqlstate[hy000]: general error: 1005 can't create table 'clouder.#sql-834_1 4' (errno: 150) (sql: alter table `users` add constraint users_package_id_f oreign foreign key (`package_id`) references `packages` (`id`)) [pdoexception] sqlstate[hy000]: general error: 1005 can't create table 'clouder.#sql-834_1 4' (errno: 150)
however, believe i've created foreign key correctly. there else i've made mistake?
i've fixed issue myself now. issue experiencing caused order of migration. create_users_table
migration comes laravel 5.2
out of box such when i've created new migrations create_packages_table
order of create_users_table
migration on first , loading before create_packages_table
. such when query trying create foreign
key can't find column on packages
table. so, renaming create_users_table
date ensure loads after create_packages_table
fixed issue.
i hope may find helpful in days.
Comments
Post a Comment