zwl1619
zwl1619

Reputation: 4232

Laravel 5.2 : `php artisan migrate` 's error

I am using Laravel 5.2 ,there is an error when I run php artisan migrate,as follows:

2016_06_12_134655_create_categories_table.php

public function up() {
   Schema::create('categories', function(Blueprint $table) {

   $table->increments('id');
   $table->string('category');
   $table->timestamps();

   });
}

2016_06_12_134659_create_goods_table.php

public function up() {
   Schema::create('goods', function(Blueprint $table) {

   $table->increments('id');
   $table->string('name');
   $table->string('unit_price');
   $table->integer('user_id')->unsigned();
   $table->tinyInteger('category_id')->unsigned();
   $table->foreign('user_id')->references('id')->on('users');
   $table->foreign('category_id')->references('id')->on('categories');
   $table->timestamps();

   });
}

$php artisan migrate

enter image description here

what should I do?

Upvotes: 0

Views: 143

Answers (3)

Mahdi Sahib
Mahdi Sahib

Reputation: 120

When you use primary key $table->Increments('id');

you should use Integer as a foreign key

    $table-> unsignedInteger('fk_id');
    $table->foreign('fk_id')->references('id')->on('table_name');

When you use primary key $table->tinyIncrements('id');

you should use unsignedTinyInteger as a foreign key

    $table-> unsignedTinyInteger('fk_id');
    $table->foreign('fk_id')->references('id')->on('table_name');

When you use primary key $table->smallIncrements('id');

you should use unsignedSmallInteger as a foreign key

    $table-> unsignedSmallInteger('fk_id');
    $table->foreign('fk_id')->references('id')->on('table_name');

When you use primary key $table->mediumIncrements('id');

you should use unsignedMediumInteger as a foreign key

    $table-> unsignedMediumInteger('fk_id');
    $table->foreign('fk_id')->references('id')->on('table_name');

Upvotes: 0

ad4s
ad4s

Reputation: 304

The referenced table categories has a primary key of type int. Keep the same in the referencing column category_id if You want to keep foreign key constraints, defined in line:

$table->foreign('category_id')->references('id')->on('categories');

Upvotes: 0

Jonathan
Jonathan

Reputation: 11494

It might be complaining about your use of tinyInteger on category_id, try setting it to integer as well - assuming your categories table exists. If it does not, you need to make sure any migrations with a foreign key constraint have their related tables migrated before them. Without seeing your categories table, I might wonder whether the datatype for your id is the same as well.

Upvotes: 1

Related Questions