【问题标题】:Error when adding foreign key of type string in Laravel在 Laravel 中添加字符串类型的外键时出错
【发布时间】:2016-12-17 05:37:46
【问题描述】:

我有两张桌子,一张优惠券和一张订单。凭证需要有一个 16 字符的字符串作为 ID,它是随机创建的。当 ID 作为整数递增时,一切正常,但是当更改为字符串时,我无法让它添加外键,出现此错误:

 [Illuminate\Database\QueryException]
 SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
 : alter table `orders` add constraint `orders_voucher_id_foreign` foreign k
 ey (`voucher_id`) references `vouchers` (`id`))

 [PDOException]
 SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

这是我的桌子:

    Schema::create('vouchers', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->string('id');
        $table->integer('value');
        $table->string('status');
        $table->timestamps();
    });

    Schema::create('orders', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->integer('event_id')->unsigned();
        $table->string('voucher_id');
        $table->timestamps();      

        $table->foreign('user_id')->references('id')->on('users');
        $table->foreign('event_id')->references('id')->on('events');
        $table->foreign('voucher_id')->references('id')->on('vouchers');
    });

非常感谢任何反馈。提前致谢。

【问题讨论】:

  • 这些架构是在同一个文件中还是在不同的文件中?

标签: php mysql laravel eloquent foreign-keys


【解决方案1】:

尝试:

$table->string('id')->unique();

【讨论】:

  • 第一次工作,圣人xox
  • np,很高兴它有帮助
猜你喜欢
  • 2017-05-06
  • 1970-01-01
  • 2019-02-07
  • 2019-10-02
  • 1970-01-01
  • 2016-05-13
  • 1970-01-01
  • 2014-02-12
相关资源
最近更新 更多