Laravel外键迁移引用字符串问题


Laravel Foreign Key Migration reference to String Issue

我想知道是否有可能在laravel迁移中添加字符串引用的外键。所以,我有关于第一个文件迁移的代码。

public function up()
{
    // roles table
    Schema::create('roles', function(Blueprint $table)
    {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->integer('level')->unsigned();
        $table->string('title');
        $table->unique('level');
    });
    // account table
    Schema::create('account', function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('acc_no');
        $table->string('acc_username');
        $table->string('acc_password');
        $table->integer('acc_roles_level')->unsigned();
        $table->softDeletes();
        $table->timestamps();
        $table->unique('acc_username');
    });

然后在第二个迁移文件上,我有这样的代码:

public function up()
{
    Schema::table('account', function(Blueprint $table)
    {
        $table->foreign('acc_roles_level')
              ->references('level')->on('roles')
              ->onUpdate('cascade')
              ->onDelete('set null');
    });
}

当迁移运行时,它显示一个错误:

SQLSTATE[HY000]:一般错误:1215无法添加外键约束(SQL:alter table `account` add constraint account_acc_roles_level_foreign外键(`acc_roles_level`(引用删除时的`roles`(`level`(更新级联时为null(

我不知道为什么我不能引用字符串列。同时,我在mysql上成功地运行了这段代码,没有出现错误:alter table account add foreign key acc_roles_level references roles(level)

有人遇到过类似的问题吗?

您必须更改迁移顺序

|-database/
|--migrations/
|---2015_02_02_141725_create_account_table.php
|---2015_03_01_234626_create_roles_table.php

应为:

|-database/
|--migrations/
|---2015_01_01_234626_create_roles_table.php
|---2015_02_02_141725_create_account_table.php

最后:

php artisan migrate

经过大量搜索,我从更改了表定义

用户表格

public function up()
{
Schema::create('users', function (Blueprint $table) {
  $table->string('user_id');
  $table->string('short_name');
  $table->string('display_name');
  $table->string('username');
  $table->string('email');
}

public function up()
{
Schema::create('users', function (Blueprint $table) {
  $table->engine = 'InnoDB'; // <- add this
  $table->string('user_id')->primary(); // <- and this
  $table->string('short_name');
  $table->string('display_name');
  $table->string('username');
  $table->string('email');
}

bonus_user

public function up()
{
Schema::create('bonus_user', function (Blueprint $table) {
  $table->engine = 'InnoDB';
  $table->string('bonus_id');
  $table->string('user_id');
});
Schema::table('bonus_user', function (Blueprint $table) {
  $table->foreign('bonus_id')->references('bonus_id')->on('bonuses')->onDelete('cascade');
  $table->foreign('user_id')->references('user_id')->on('users')->onDelete('cascade');
});

}

innoDB我从这里得到了SO laravel外键迁移引用字符串问题(见答案2(

primary((我从这里得到,在这里输入链接描述(尽管我没有遵循答案的任何其他部分,因为我必须将主键作为字符串,因为它是作为24个字符的字符串提供给我的!(

我认为这两个更改是协同工作的,因为它不仅仅适用于InnoDB引擎的更改。

迁移顺序也可能是解决方案的一部分,但由于引用此外键的bonus_user表是在原始用户表迁移后生成的,因此创建顺序问题对我来说不是问题!

在我将primary((添加到user_id列后,它第一次工作了