我试图在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');
}

关于我做错了什么,我现在想要得到这个,因为我有很多表,我需要创建例如用户,客户端,项目,任务,状态,优先级,类型,团队。理想情况下,我想创建表持有这些数据与外键,即clients_project和project_tasks等。

希望有人能帮我开始。


当前回答

你应该这样写

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');
    });     
}

外键字段应不签名,希望对您有帮助!!

其他回答

我在laravel 5.8有这个问题,我修复了这个代码,如laravel文档中所示,在我添加外键的地方。

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

然后我运行$ PHP artisan migrate:refresh

由于这种语法相当冗长,Laravel提供了额外的、更简洁的方法,使用约定来提供更好的开发体验。上面的例子可以这样写:

Schema::table('posts', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained()->onDelete('cascade');
});

注意:当Laravel设置一个表使用

$table->increments('id');

这在大多数迁移中是标准的,这将设置一个无符号整数字段。因此,当从另一个表对这个字段进行外部引用时,确保在引用表中,您将字段设置为UnsignedBigInteger,而不是(我假设是一个)UnsignedBigInteger字段。

例如:在迁移文件2018_12_12_123456_create_users_table.php中:

Schema::create('users', function (Blueprint $table){
    $table->increments('id');
    $table->string('name');
    $table->timestamps();

然后在迁移文件2018_12_12_18000000_create_permissions_table.php中,该文件将外部引用设置回用户:

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');
}

另一个原因可能是DB引擎类型。Laravel默认使用MyISAM引擎。所以如果你需要强制外键引用检查,你应该使用InnoDB作为你的引擎。

这个设置在config/database.php文件中。将引擎改为'engine' => 'InnoDB'

另外,如果您试图对现有表执行此操作,请使用

DB::statement("ALTER TABLE ' {$tableName} ' ENGINE = 'InnoDB'");

在最初的问题之后的几年,我使用laravel 5.1,我有同样的错误,因为我的迁移是由计算机生成的,所有的日期代码都是相同的。我遍历了所有提出的解决方案,然后重构以找到错误源。

在遵循laracast和阅读这些文章时,我相信正确答案与Vickies的答案相似,除了您不需要添加单独的模式调用。你不需要设置Innodb,我假设laravel现在正在做这件事。

迁移只需要正确地计时,这意味着您将(稍后)修改需要外键的表的文件名中的日期代码。另外,对于不需要外键的表,降低数据码。

修改日期码的好处是您的迁移代码将更容易阅读和维护。

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

但是我有几百个表,所以在最后,我有最后一个表用于外键。只是为了让事情顺利进行。我假设我将把它们拉到正确的文件中,并在测试时修改数据码。

例如:文件2016_01_18_999999_create_product_options_table。它需要创建产品表。看一下文件名。

 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');
}

产品表:首先需要迁移这个表。2015年_01_18_000000_create_products_table

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_9999_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');
//        });

你应该这样写

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');
    });     
}

外键字段应不签名,希望对您有帮助!!