Laravel 5.5迁移:无法创建外键

时间:2018-02-01 20:42:22

标签: laravel laravel-5.5

所以我有三张桌子。客户/网站/用户。客户有很多站点。客户有很多用户。用户/站点属于客户端。挺直的。遗憾的是,我们正在从一个认为使用字符串密钥是个好主意的人那里导入Site / Client表的信息。

以下是我的迁移 -

这是客户表:

Schema::create('clients', function (Blueprint $table) {
    $table->string('id', 25)->primary();
    $table->char('number', 6)->unique();
    $table->string('name', 50)->unique();
    $table->timestamps();
});

这是网站表:

public function up()
{
    Schema::create('sites', function (Blueprint $table) {
        $table->string('id', 25)->primary();
        $table->string('name', 30)->unique();
        $table->string('number', 10)->unique();
        $table->string('address_1', 60);
        $table->string('address_2', 60)->nullable();
        $table->string('city', 30);
        $table->string('state', 3);
        $table->string('postal_code', 10);
        $table->string('country', 30);
        $table->string('weather_code')->nullable();
        $table->decimal('dimension', 18, 0)->nullable();
        $table->string('dimension_uom', 10)->nullable();
        $table->string('client_id', 25);
        $table->softDeletes();            
        $table->timestamps();

        // Belongs To Client
        $table->foreign('client_id')->references('id')->on('clients');
    });
}

这是用户表:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('client_id', 25);
        $table->rememberToken();
        $table->timestamps();

        // Belongs To Client
        $table->foreign('client_id')->references('id')->on('clients');
    });
}

然而,当我运行这些时,我收到以下错误:

  

SQLSTATE [HY000]:常规错误:1215无法添加外键约束(SQL:alter table users添加约束users_client_id_foreign外键(client_id)引用clientsid))

     

SQLSTATE [HY000]:常规错误:1215无法添加外键约束

如果我删除了对用户的外键尝试,但是将其保留在网站中则可以正常工作。我在两者中做的完全相同但由于某种原因它在网站而不是在用户中工作。知道为什么吗?

1 个答案:

答案 0 :(得分:3)

这里的问题是当您运行迁移user表时首先创建表,并且在sqwaks之前找不到client表。因此,请确保在clients之前运行users迁移。更改时间戳。

  1. 首先进行客户端迁移

  2. 之后的用户迁移
相关问题