简体   繁体   中英

Laravel 4 Migration - Cannot add foreign key constraint

Here's my migration code:

public function up()
{
    Schema::create('foos', function(Blueprint $table) {
        // Primary key
        $table->increments('id');

        // Standard
        $table->engine = 'InnoDB';
        $table->timestamps();
        $table->softDeletes();
    });

    Schema::create('bars', function(Blueprint $table) {
        // Primary key
        $table->increments('id');

        // Define foreign key
        $table->integer('foo_id')->unsigned;

        // Foreign key contraints
        // NOTE: causes "General error: 1215 Cannot add foreign key constraint"
        // $table->foreign('foo_id')->references('id')->on('foos');

        // Standard
        $table->engine = 'InnoDB';
        $table->timestamps();
        $table->softDeletes();
    });
}

public function down()
{
    Schema::drop('foos');
    Schema::drop('bars');
}

When the code to define the foreign key constraint is not commented out, I get the following error on the command line: General error: 1215 Cannot add foreign key constraint .

Any ideas what I am doing wrong?

$table->integer('foo_id')->unsigned;

should be

$table->integer('foo_id')->unsigned();

or you can use short version:

$table->unsignedInteger('foo_id');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM