简体   繁体   中英

SQLSTATE[HY000]: General error: 1005 Can't create table - Laravel 4

I get this error when I do php artisan migrate. Is there something wrong in my migration files? Or is it possible my models are wrong coded? But the migrations should work even there is something wrong in the models?

[Exception]                                                                  
  SQLSTATE[HY000]: General error: 1005 Can't create table 'festival_aid.#sql-  
  16643_2033' (errno: 150) (SQL: alter table `gigs` add constraint gigs_band_  
  id_foreign foreign key (`band_id`) references `bands` (`band_id`) on delete  
   cascade) (Bindings: array (                                                 
  ))

[PDOException]                                                               
  SQLSTATE[HY000]: General error: 1005 Can't create table 'festival_aid.#sql-  
  16643_2033' (errno: 150)

gigs migration

public function up()
    {
        Schema::create('gigs', function($table)
        {
            $table->increments('gig_id');

            $table->dateTime('gig_startdate');

            $table->integer('band_id')->unsigned();
            $table->integer('stage_id')->unsigned();

            $table->foreign('band_id')
                ->references('band_id')->on('bands')
                ->onDelete('cascade');

            $table->foreign('stage_id')
                ->references('stage_id')->on('stages')
                ->onDelete('cascade');
        });

    public function down()
    {
        Schema::table('gigs', function($table)
        {
            Schema::drop('gigs');
            $table->dropForeign('gigs_band_id_foreign');
            $table->dropForeign('gigs_stage_id_foreign');
        });
    }

bands migration

public function up()
    {
        Schema::create('bands', function($table)
        {
            $table->increments('band_id');

            $table->string('band_name');
            $table->text('band_members');
            $table->string('band_genre');
            $table->dateTime('band_startdate');
        });
    }

    public function down()
    {
        Schema::table('bands', function(Blueprint $table)
        {
            Schema::drop('bands');
        });
    }

Model Band

<?php

class Band extends Eloquent {

    protected $primaryKey = 'band_id';

    public function gig()
    {
        return $this->hasOne('Gig', 'band_id', 'band_id');
    }
}

Model Gig

<?php

class Gig extends Eloquent {
    protected $primaryKey = 'gig_id';

    public function gig()
    {
        return $this->belongsTo('Band', 'band_id', 'band_id');
    }

    public function stage()
    {
        return $this->belongsTo('Stage', 'stage_id', 'stage_id');
    }
}

You must first create the table, then create the foreign keys:

Schema::create('gigs', function($table)
{
    $table->increments('gig_id');

    $table->dateTime('gig_startdate');

    $table->integer('band_id')->unsigned();
    $table->integer('stage_id')->unsigned();
});

Schema::table('gigs', function($table)
{
    $table->foreign('band_id')
        ->references('band_id')->on('bands')
        ->onDelete('cascade');

    $table->foreign('stage_id')
        ->references('stage_id')->on('stages')
        ->onDelete('cascade');
});

And your bands table should migrate first, since the gigs is referencing it.

While this doesn't apply to OP, others might have this issue:

From the bottom of the Laravel Schema docs :

Note: When creating a foreign key that references an incrementing integer, remember to always make the foreign key column unsigned.

You can do this via $table->integer('user_id')->unsigned(); when creating your table in the migration file.

Took me a few minutes to realize what was happening.

对于那些其他答案没有帮助的人,当您尝试对不可为空的列使用'SET_NULL'操作时,也会引发相同的错误。

As said by Andrew by making the reference on the table as this:

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

It should work.

Nothing of the above worked for me ! But this did : I just changed integer to unsignedInteger

$table->unsignedBigInteger('user_id')->unsigned();

for those who are still having this issue, make sure the field you setting as foreign key is a primary key or should be unique since a foreign key can only be a primary or unique field. see sample below

Schema::create('users', function (Blueprint $table) {
  $table->increments('id');
  $table->string('username',25)->unique();
 });

Schema::create('another_table', function (Blueprint $table) {
   $table->increments('id');
   $table->string('name', 25);
   $table->foreign('name')->references('username')->on('users')
 });
        $table->integer('band_id')->unsigned();
        $table->integer('stage_id')->unsigned();

In laravel 5.8, the users_table uses bigIncrements('id') data type for the primary key. So that when you want to refer a foreign key constraint your band_id,stage_id column needs to be unsignedBigInteger('stage_id') and band_id type.

The manager also tested this way.

I had a similar problem. You must use bigInteger to solve this problem:

$table->bigInteger('user_id')->unsigned();

This seems to be a general foreign key issue error. For me I got it when I switched the arguments in the references and on methods. I had:

$table->foreign('user_id')->references('users')->on('id');

instead of:

$table->foreign('user_id')->references('id')->on('users');

I just fixed this problem by making pointing to Laravel that the field is unique using unique() .

Example:

Schema::create('branches', function (Blueprint $table) {
            $table->increments('id');
            /* This fields serves as foriegn key on functions 
            table and it must follow the database **key rules**
            by being unique */
            $table->string('branch_code')->unique();
            $table->string('branch_name');
            $table->string('branch_address');
            $table->timestamps();
        });

Functions table:

    Schema::create('functions', function (Blueprint $table) {
        $table->increments('id');
        $table->string('branch_code');
        $table->string('function');
        $table->timestamps();
        //Reference to branch_code on branches table
        $table->foreign('branch_code')->references('branch_code')->on('branches');

    });

我在 config/database 'engine' => 'InnoDB',更改为'engine' => null,并且可以正常工作

You can use

$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('users')->on('id');

BigInt has datatype of bigint(20) but integer has datatype of int(10). Though both of those are unsigned integer, 'Length/Values' does not match.

For Laravel 6.X use this format.

$table->unsignedBigInteger('dest_id')->unsigned();

$table->foreign('dest_id')->references('id')->on('destinations')->onDelete('cascade');

Changing from:

$table->unsignedInteger('user_id')->unique();

To:

$table->unsignedBigInteger('user_id')->unique();

worked for me

The foreign key must use either unsignedInterger or unsignedBigInterger

exam:

public function up()
{
    Schema::create('likes', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('user_id');
        $table->unsignedInteger('post_id');
        $table->string('post_type');
        $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
        $table->timestamps();
    });
}

You may also specify the desired action for the "on delete" and "on update" properties of the constraint:

$table->foreignId('user_id')
  ->constrained()
  ->onUpdate('cascade')
  ->onDelete('cascade');

I think you should checkout the referenced tables , for example you could get such errors if you pass the values . This could be the reason $table->foreign('course_id')->references('course_id')->on('ptable'); which is wrong but $table->foreign('course_id')->references('course_id')->on('ptable'); which is wrong but $table->foreign('course_id')->references('level_id')->on('ptable');` is correct

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