Reputation: 2658
Below are my migrations
The users table have a relation with the customer table
In user:
$table->integer('customer_id')->unsigned();
$table->foreign('customer_id')->references('id')->on('customers');
When i call php artisan migrate:refresh --seed
, artisan given me the following error:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table `users` add constraint `users_customer_id_foreign` foreign ke
y (`customer_id`) references `customers` (`id`))
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
Because the customers table does not exists... (obvious)
Is there a way to solve this problem? I know changing the date of the files will fix this but there should be a beter approach
Upvotes: 0
Views: 172
Reputation:
If you had set one field as "Unsigned" and other one not. Once you should set both columns to Unsigned it works.
Upvotes: 0
Reputation: 1022
Try to make it separately.
public function up()
{
Schema::create('users', function(Blueprint $table) {
$table->increments('id');
$table->integer('costumer_id')->unsigned();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::table('users', function($table) {
$table->foreign('costumer_id')->references('id')->on('costumers');
});
}
Another thing you can try(since laravel 5.3):
unsignedInteger('column_name') instead of ('column_name')-unsigned()
Upvotes: 0
Reputation: 821
You have to create the table you're referencing to before adding the foreign key. A solution would be to remove the foreign key constraint from your user table migration and create a new migration which adds the foreign key constraints.
Upvotes: 2