外键错误形成

时间:2017-07-30 10:48:26

标签: mysql laravel laravel-migrations

当我将主键从增量更改为字符串(user_id)时,我的迁移中出现了错误。我似乎没有看到我哪里出错了。我的迁移文件没问题,直到我从( - >增量和另一个 - >整数)更改为( - >两者都是字符串)。问题是当它迁移clanmembers表时,它说外键不正确

之前我的代码。似乎没关系,cmd中的迁移没有错误

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('user_id');
        $table->string('fname', 50);
        $table->string('lname', 50);
        $table->integer('age');
        $table->string('gender', 10);
        $table->string('address', 50);
        $table->timestamps();
    });
}

public function up()
{
    Schema::create('clanmembers', function (Blueprint $table) {
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('user_id')->on('users')->onDelete('cascade');
        $table->integer('clan_id')->unsigned();
        $table->foreign('clan_id')->references('clan_id')->on('clans')->onDelete('cascade');
        $table->string('bandrole', 50);
        $table->timestamps();
    });
}

我的代码现在我改变了 - >增量和 - >整数到两个 - >字符串

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->string('user_id');
        $table->string('fname', 50);
        $table->string('lname', 50);
        $table->integer('age');
        $table->string('gender', 10);
        $table->string('address', 50);
        $table->timestamps();
    });
}

public function up()
{
    Schema::create('clanmembers', function (Blueprint $table) {
        $table->string('user_id');
        $table->foreign('user_id')->references('user_id')->on('users')->onDelete('cascade');
        $table->integer('clan_id')->unsigned();
        $table->foreign('clan_id')->references('clan_id')->on('clans')->onDelete('cascade');
        $table->string('clanrole', 50);
        $table->timestamps();
    });
}

2 个答案:

答案 0 :(得分:2)

表一

 public function up()
    {
        //
       Schema::create('table_1', function (Blueprint $table) {
        $table->string('user_id',100);
        $table->string('fname', 50);
        $table->string('lname', 50);
        $table->integer('age');
        $table->string('gender', 10);
        $table->string('address', 50);
        $table->timestamps();
        $table->primary(['user_id']);
    });
   }

表二

public function up()
    {
        //
       Schema::create('clanmembers', function (Blueprint $table) {
        $table->string('user_id',100);
        $table->foreign('user_id')->references('user_id')->on('table_1')
        ->onDelete('cascade');
        $table->timestamps();
    });
   }

答案 1 :(得分:0)

你需要设置字符串长度 $ table-> string(' user_id',100); 对于intiger类型,如果未设置长度,则自动转为默认值11。 但对于字符串,您需要设置它。

相关问题