Laravel 迁移:无法添加外键约束

Laravel 迁移:无法添加外键约束,laravel,laravel-4,foreign-keys,migration,eloquent,Laravel,Laravel 4,Foreign Keys,Migration,Eloquent,我正在尝试在Laravel中创建外键,但是当我使用artisan迁移表时,出现以下错误: [Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL : alter table `priorities` add constraint priorities_user_id_foreign foreign key (`user_id`

我正在尝试在Laravel中创建外键,但是当我使用
artisan
迁移表时,出现以下错误:

[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table `priorities` add constraint priorities_user_id_foreign foreign 
key (`user_id`) references `users` (`id`))     
我的迁移代码如下:

优先级迁移文件

public function up()
{
    //
    Schema::create('priorities', function($table) {
        $table->increments('id', true);
        $table->integer('user_id');
        $table->foreign('user_id')->references('id')->on('users');
        $table->string('priority_name');
        $table->smallInteger('rank');
        $table->text('class');
        $table->timestamps('timecreated');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    //
    Schema::drop('priorities');
}
用户迁移文件

public function up()
{
    //
    Schema::table('users', function($table)
    {
    $table->create();
    $table->increments('id');
    $table->string('email');
    $table->string('first_name');
    $table->string('password');
    $table->string('email_code');
    $table->string('time_created');
    $table->string('ip');
    $table->string('confirmed');
    $table->string('user_role');
    $table->string('salt');
    $table->string('last_login');

    $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    //
        Schemea::drop('users');
}
任何关于我做错了什么的想法,我现在就想知道,因为我有很多表需要创建,例如用户、客户、项目、任务、状态、优先级、类型、团队。理想情况下,我希望创建使用外键保存此数据的表,即
客户机\项目
项目\任务


希望有人能帮助我开始

分两步添加,最好也取消签名:

public function up()
{
    Schema::create('priorities', function($table) {
        $table->increments('id', true);
        $table->integer('user_id')->unsigned();
        $table->string('priority_name');
        $table->smallInteger('rank');
        $table->text('class');
        $table->timestamps('timecreated');
    });

   Schema::table('priorities', function($table) {
       $table->foreign('user_id')->references('id')->on('users');
   });

}

问题已经回答了,但希望这能帮助其他人


发生此错误是因为我在迁移表的原始表中以主键形式存在外键之前,首先创建了包含外键的迁移表。迁移按照运行
migrate:make
后生成的文件名指示的顺序执行。例如
2014\u 05\u 10\u 165709\u create\u student\u table.php

解决方案是按照此处的建议,将具有外键的文件重命名为比具有主键的文件更早的时间:


我想我还必须添加
$table->engine='InnoDB'

我发生此错误是因为-当我尝试创建的表是InnoDB时-我尝试将其关联到的外部表是MyISAM表

在我的例子中,问题是主表中已经有记录,我强制新列不为NULL。因此,将->nullable()添加到新列就成功了。在问题的例子中是这样的:

public function up()
{
    Schema::create('priorities', function($table) {
        $table->increments('id', true);
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->string('priority_name');
        $table->smallInteger('rank');
        $table->text('class');
        $table->timestamps('timecreated');
    });
}
$table->integer('user_id')->unsigned()->nullable()

或:

$table->unsignedInteger('user_id')->nullable()


希望这对别人有帮助

在我的例子中,我引用了字符串
用户id
列上的整数
id
列。我改变了:

$table->string('user\u id')

致:

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


希望它能帮助别人

为了在laravel中添加外键约束,我做了以下工作:

  • 按如下方式创建要作为外键的列:

    $table->integer('column_name')->unsigned(); $table->integer('column_name')->unsigned()
  • 在(1)之后立即添加约束线,即

    $table->integer('column_name')->unsigned(); $table->foreign('column_name')->references('pk_of_other_table')->on('other_table')
    在我的例子中,问题在于迁移时间,创建迁移时要小心,首先创建子迁移,而不是基本迁移。因为若首先创建具有外键的基本迁移,将查找子表,而不会有表抛出异常

    更多信息:

    创建迁移时,它的开头有一个时间戳。假设您已经创建了一个迁移cat,因此它看起来像
    2015\u 08\u 19\u 075954\u the\u cats\u time.php
    ,它有以下代码

    <?php
    
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;
    
    class TheCatsTime extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('cat', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');  
                $table->date('date_of_birth');
                $table->integer('breed_id')->unsigned()->nullable(); 
            });
    
            Schema::table('cat', function($table) {
            $table->foreign('breed_id')->references('id')->on('breed');
          });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::drop('cat');
        }
    }
    

    除非创建相关表,否则无法添加关系。Laravel按迁移文件的日期运行迁移顺序。所以,如果您想创建一个与第二个迁移文件中存在的表的关系,它将失败

    我也面临同样的问题,所以我最后又创建了一个迁移文件来指定所有关系

    Schema::table('properties', function(Blueprint $table) {
            $table->foreign('user')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('area')->references('id')->on('areas')->onDelete('cascade');
            $table->foreign('city')->references('id')->on('cities')->onDelete('cascade');
            $table->foreign('type')->references('id')->on('property_types')->onDelete('cascade');
        });
    
        Schema::table('areas', function(Blueprint $table) {
            $table->foreign('city_id')->references('id')->on('cities')->onDelete('cascade');
        });
    

    在最初的问题提出几年后,使用Laravel5.1,我在这里遇到了同样的错误,因为我的迁移是用相同的日期代码由计算机生成的。我检查了所有建议的解决方案,然后进行重构以找到错误源

    在下面的Laracast中,以及在阅读这些帖子时,我相信正确的答案与Vickies的答案类似,只是不需要添加单独的模式调用。您不需要将表设置为Innodb,我假设laravel正在这样做

    迁移只需要正确计时,这意味着您将在需要外键的表的文件名中修改日期代码up(稍后)。或者,降低不需要外键的表的日期代码

    修改日期代码的优点是迁移代码更易于阅读和维护

    到目前为止,我的代码通过向上调整时间代码来推动需要外键的迁移

    然而,我有数百个表,所以在最后我有最后一个表,只用于外键。只是为了让事情顺利进行。我假设我会将它们拉入正确的文件,并在测试它们时修改日期代码

    例如:文件2016\u 01\u 18\u9999\u创建\u产品\u选项\u表格。这一个需要创建products表。看看文件名

     public function up()
    {
        Schema::create('product_options', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('product_attribute_id')->unsigned()->index();
            $table->integer('product_id')->unsigned()->index();
            $table->string('value', 40)->default('');
            $table->timestamps();
            //$table->foreign('product_id')->references('id')->on('products');
            $table->foreign('product_attribute_id')->references('id')->on('product_attributes');
            $table->foreign('product_id')->references('id')->on('products');
    
    
        });
    }
    
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('product_options');
    }
    
    products表:这需要首先迁移。2015年1月18日000000日创建产品表

    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
    
            $table->string('style_number', 64)->default('');
            $table->string('title')->default('');
            $table->text('overview')->nullable();
            $table->text('description')->nullable();
    
    
            $table->timestamps();
        });
    }
    
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('products');
    }
    
    最后是我临时用来解决问题的文件,我将在为我命名为9999_99_99_9999; u create_foreign_keys.php的模型编写测试时对其进行重构。这些钥匙在我取出时会被注释,但你明白了

        public function up()
        {
    //        Schema::table('product_skus', function ($table) {
    //            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
    //    });
    
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
    //        Schema::table('product_skus', function ($table)
    //        {
    //            $table->dropForeign('product_skus_product_id_foreign');
    //        });
    

    我知道这是一个老问题,但请确保如果您使用的是参考文献,则定义了正确的支持引擎。为两个表设置innodb引擎,并为引用列设置相同的数据类型

    $table->engine = 'InnoDB';
    
    这么简单

    如果您第一次创建了
    'priorities'
    迁移文件,则Laravel首先运行
    'priorities'
    ,而
    'users'
    表不存在

    如何向不存在的表添加关系

    解决方案:
    “优先级”
    表中拉出外键代码。您的迁移文件应如下所示:

    public function up()
    {
        Schema::create('priorities', function($table) {
            $table->increments('id', true);
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');
            $table->string('priority_name');
            $table->smallInteger('rank');
            $table->text('class');
            $table->timestamps('timecreated');
        });
    }
    

    并添加到一个新的迁移文件中,这里是它的名称
    public function up()
    {        
        Schema::table('priorities', function (Blueprint $table) {          
            $table->foreign('user_id')
                  ->references('id')
                  ->on('users');                        
        });
    }
    
    $table->unsignedInt('column_name');
    $table->foreign('column_name')->references('id')->on('table_name');
    
    public function up()
    {
        Schema::create('priorities', function($table) {
            $table->increments('id', true);
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');
            $table->string('priority_name');
            $table->smallInteger('rank');
            $table->text('class');
            $table->timestamps('timecreated');
        });
    }
    
    $table->increments('column_name'); //is INTEGER and UNSIGNED
    
    $table->integer('column_forein_name')->unsigned(); //this must be INTEGER and UNSIGNED
    $table->foreign('column_forein_name')->references('column_name')->on('first_table_name');
    
    $table->mediumIncrements('column_name'); //is MEDIUM-INTEGER and UNSIGNED
    
    $table->mediumInteger('column_forein_name')->unsigned(); //this must be MEDIUM-INTEGER and UNSIGNED
    $table->foreign('column_forein_name')->references('column_name')->on('first_table_name');
    
            $table->integer('user_id', false, true);
    
    $table->bigIncrements('id');
    
    $table->unsignedInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    
    $table->unsignedBigInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    
    composer dump-autoload
    
    public function up()
    {
        //
         Schema::create('priorities', function($table) {
            $table->increments('id', true);
            $table->integer('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->string('priority_name');
            $table->smallInteger('rank');
            $table->text('class');
            $table->timestamps('timecreated');
        });
     }
    
     /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
        Schema::drop('priorities');
    }
    
    app/database/migrations
    
    $table->increments('id');
    
    Schema::create('users', function (Blueprint $table){
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    
    Schema::create('permissions', function (Blueprint $table){
        $table->increments('id');
        $table->UnsignedInteger('user_id'); // UnsignedInteger = "increments" in users table
        $table->boolean('admin');
        $table->boolean('enabled');
        $table->timestamps();
    
        // set up relationship
        $table->foreign('user_id')->reference('id')->on('users')->onDelete('cascade');
    }
    
    Schema::create('schools', function (Blueprint $table) {
        $table->integer('dcid')->index()->unque();
        $table->integer('school_number')->index(); // The important thing is that this is indexed
        $table->string('name');
        $table->string('abbreviation');
        $table->integer('high_grade');
        $table->integer('low_grade');
        $table->timestamps();
        $table->primary('dcid');
    });
    
    Schema::create('students', function (Blueprint $table) {
          $table->increments('id');
          $table->integer('dcid')->index()->unique()->nullable();
          $table->unsignedInteger('student_number')->nullable();
          $table->integer('schoolid')->nullable();
          $table->foreign('schoolid')->references('school_number')->on('schools')->onDelete('set null');
          // ...
    });
    
    1. Users table
    
        Schema::create('users', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('name');
                $table->string('email')->unique();
                $table->timestamp('email_verified_at')->nullable();
                $table->string('password');
                $table->rememberToken();
                $table->timestamps();
            });
    
    2. Roles Table
        Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name')->unique();
            $table->string('display_name')->nullable();
            $table->string('description')->nullable();
            $table->timestamps();
        });
    
    3. Table role_user
    Schema::create('role_user', function (Blueprint $table) {
                $table->unsignedBigInteger('user_id');
                $table->unsignedBigInteger('role_id');
                $table->foreign('user_id')->references('id')->on('users')
                    ->onUpdate('cascade')->onDelete('cascade');
                $table->foreign('role_id')->references('id')->on('roles')
                    ->onUpdate('cascade')->onDelete('cascade');
                $table->primary(['user_id', 'role_id']);
            });
    
    // ...
    
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
    
            $table->bigIncrements('id');
    
            $table->string('full_name');
            $table->string('email');
            $table->timestamps();
        });
    }
    
    // ...
    
    public function up()
    {
        Schema::create('role_user', function (Blueprint $table) {
    
            // this line throw QueryException "SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint..."
            // $table->integer('user_id')->unsigned()->index();
    
            $table->bigInteger('user_id')->unsigned()->index(); // this is working
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    }
    
    $table->engine = 'InnoDB';
    
    $table->engine = 'MyISAM';
    
    SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
    
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedInteger('business_unit_id')->nullable();
    
            $table->string('name', 100);
    
            $table->foreign('business_unit_id')
                    ->references('id')
                    ->on('business_units')
                    ->onDelete('cascade');
    
            $table->timestamps();
            $table->softDeletes();
            $table->engine = 'InnoDB'; # <=== see this line
        });
    }
    
    public function up()
    {
        Schema::create('transactions', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->float('amount', 11, 2);
            $table->enum('transaction type', ['debit', 'credit']);
            $table->bigInteger('customer_id')->unsigned();      
            $table->timestamps();                 
        });
    
        Schema::table('transactions', function($table) {
            $table->foreign('customer_id')
                  ->references('id')->on('customers')
                  ->onDelete('cascade');
        });     
    }
    
    $table->unsignedBigInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    
    Schema::table('posts', function (Blueprint $table) {
        $table->foreignId('user_id')->constrained()->onDelete('cascade');
    });
    
    public function up()
    {
        Schema::create('doc_education', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('uni_id')->unsigned()->nullable();
            $table->timestamps();
        });
    }
    
        Schema::create('doc_universties', function (Blueprint $table) {
            $table->increments('id');
            $table->string('uni_name');
            $table->string('location')->nullable();
            $table->timestamps();
    
            //
        });
    
    
    
    Schema::table('doc_education', function(Blueprint $table) {
            $table->foreign('uni_id')->references('id')
            ->on('doc_universties')->onDelete('cascade');
        });
    
        $tables = [
            'table_1',
            'table_2'
        ];
    
        foreach ($tables as $table) {
            \DB::statement('ALTER TABLE ' . $table . ' ENGINE = InnoDB');
        }