MySQL 1215无法添加外键约束 - Laravel 5

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL 1215无法添加外键约束 - Laravel 5相关的知识,希望对你有一定的参考价值。

我坚持这个臭名昭着的错误,无法弄清楚出了什么问题。我正在尝试建立两个表orderspayments之间的关系,其迁移定义为:

class CreateOrdersTable extends Migration
{
    public function up()
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();

            $table->integer('customer_id')->unsigned();
            $table->integer('partner_id')->unsigned();

            $table->string('status', 20)->default(Order::getDefaultStatus());
            $table->string('paid', 20)->default('no');

            $table->decimal('visitation_charges', 20, 2)->default(0); 
            $table->decimal('taxes', 20, 2)->default(0);
            $table->decimal('charges', 20, 2)->default(0);
            $table->decimal('discount', 20, 2)->default(0);
            $table->decimal('total', 20, 2)->default(0);

            $table->foreign('customer_id')->references('id')
                  ->on('customers')->onDelete('cascade')
                  ->onUpdate('cascade');
            $table->foreign('partner_id')->references('id')
                  ->on('partners')->onDelete('cascade')
                  ->onUpdate('cascade');
        });
    }

    public function down()
    {
        Schema::dropIfExists('orders');
    }
}

class CreatePaymentsTable extends Migration
{
    public function up()
    {
        Schema::create('payments', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();

            $table->integer('order_id')->unsigned();
            $table->string('gateway', 100);
            $table->string('transaction_id', 100);
            $table->decimal('amount', 20, 2);
            $table->string('status', 20)->default(Payment::getDefaultStatus());
            $table->string('comments', 2000)->nullable();

            $table->foreign('order_id')->references('id')
                  ->on('orders')->onDelete('set null')
                  ->onUpdate('cascade');
        });
    }

    public function down()
    {
        Schema::dropIfExists('payments');
    }
}

我得到的错误是:

[IlluminateDatabaseQueryException]                                                                   
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `payments` add constraint `payments_order_id_foreign` foreign key (`order_id`) references `orders` (`id`) on delete set null on update cascade)

我还验证了表引擎,列类型,字符集等是相同的(以下是show create的输出):

| orders | CREATE TABLE `orders` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `customer_id` int(10) unsigned NOT NULL,
  `partner_id` int(10) unsigned NOT NULL,
  `status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'created',
  `paid` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'no',
  `visitation_charges` decimal(20,2) NOT NULL DEFAULT '0.00',
  `taxes` decimal(20,2) NOT NULL DEFAULT '0.00',
  `charges` decimal(20,2) NOT NULL DEFAULT '0.00',
  `discount` decimal(20,2) NOT NULL DEFAULT '0.00',
  `total` decimal(20,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`id`),
  KEY `orders_customer_id_foreign` (`customer_id`),
  KEY `orders_partner_id_foreign` (`partner_id`),
  CONSTRAINT `orders_customer_id_foreign` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `orders_partner_id_foreign` FOREIGN KEY (`partner_id`) REFERENCES `partners` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

| payments | CREATE TABLE `payments` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `order_id` int(10) unsigned NOT NULL,
  `gateway` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
  `transaction_id` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
  `amount` decimal(20,2) NOT NULL,
  `status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'pending',
  `comments` varchar(2000) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

不知道我哪里出错了。 :/

答案

您不能为声明为ON DELETE SET NULL的列创建外键NOT NULL

该列不能为NULL。

如果您执行以下任一操作,则外键有效:

  • 省略ON DELETE SET NULLalter table `payments` add constraint `payments_order_id_foreign` foreign key (`order_id`) references `orders` (`id`) on update cascade;
  • 修改列以允许NULL: alter table payments modify order_id int(10) unsigned null;
另一答案

最好为外键构建另一个迁移:

php artisan make:migration add_foreign_key_to_payment_table --table=payments

所以在此迁移中添加支付外键,然后运行php artisan migrate

如果错误仍然存​​在,您必须手动删除订单和付款表,并从迁移表中删除它们,然后再次添加。

我希望这能帮到您。美好的一天! :)

另一答案

在order_id列上添加nullable()。如下。你的错误将消失。

class CreatePaymentsTable extends Migration
{
    public function up()
    {
        Schema::create('payments', function (Blueprint $table) {
        // your others columns
         $table->integer('order_id')->unsigned()->nullable();
    }
}

以上是关于MySQL 1215无法添加外键约束 - Laravel 5的主要内容,如果未能解决你的问题,请参考以下文章

MySQL 错误 1215:无法添加外键约束

一般错误:1215 无法添加外键约束,Laravel 5 & MySQL

MySQL : ERROR 1215 (HY000): 无法添加外键约束

MYSQL Workbench - 错误:错误 1215:无法添加外键约束

MySQL 1215无法添加外键约束 - Laravel 5

我无法将我的 SQL 表从 Adminer 导入 MySQL Workbench 而不会出现错误:第 9 行的错误 1215 (HY000):无法添加外键约束